malloc的或正常的数组定义? [英] Malloc or normal array definition?

查看:135
本文介绍了malloc的或正常的数组定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候用malloc而不是普通的数组定义用C?

我不明白之间的区别:

  int类型的[3] = {1,2,3}
int数组[的sizeof(A)/ sizeof的(INT)

  =阵列(INT *)malloc的(的sizeof(int)的*的sizeof(a)条);


解决方案

在一般情况下,使用的malloc()时:


  • 阵列太大而被放置在栈上

  • 阵列的寿命则创建,其中必须经受住的范围

否则,使用堆栈分配的数组。

When shall i use malloc instead of normal array definition in C?

I can't understand the difference between:

int a[3]={1,2,3}
int array[sizeof(a)/sizeof(int)]

and:

array=(int *)malloc(sizeof(int)*sizeof(a));

解决方案

In general, use malloc() when:

  • the array is too large to be placed on the stack
  • the lifetime of the array must outlive the scope where it is created

Otherwise, use a stack allocated array.

这篇关于malloc的或正常的数组定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆