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