我什么时候应该在C中使用malloc?

时间:2011-03-31 09:27:31

标签: c malloc

  

可能重复:
  When should I use malloc in C and when don't I?

嗨,我是C语言的新手,发现了malloc函数。我应该什么时候使用它?在我的工作中,有人说你必须在这种情况下使用malloc,但是其他人说在这种情况下你不需要使用它。所以我的问题是:我什么时候应该使用malloc?这对你来说可能是一个愚蠢的问题,但对于一个不熟悉C的程序员来说,这很令人困惑!

3 个答案:

答案 0 :(得分:11)

使用malloc(),您可以“即时”分配内存。如果您事先不知道需要多少内存,这将非常有用。

如果您知道,可以进行静态分配,例如

int my_table[10]; // Allocates a table of ten ints.

如果您不知道需要存储多少个整数,则可以

int *my_table;
// During execution you somehow find out the number and store to the "count" variable
my_table = (int*) malloc(sizeof(int)*count);
// Then you would use the table and after you don't need it anymore you say
free(my_table);

答案 1 :(得分:9)

一个主要用途是,当您处理项目列表时,您不知道列表的大小。

答案 2 :(得分:7)

相关问题