Malloc 或普通数组定义? [英] Malloc or normal array definition?

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

问题描述

我什么时候应该在 C 中使用 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)]

和:

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

推荐答案

一般来说,在以下情况下使用malloc():

In general, use malloc() when:

  • 数组太大,无法放入堆栈
  • 数组的生命周期必须超过创建它的作用域

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

Otherwise, use a stack allocated array.

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

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