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

kev*_*vin 6 c malloc

可能重复:
我什么时候应该在C中使用malloc,什么时候不使用?

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

Mak*_*kis 11

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

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

int my_table[10]; // Allocates a table of ten ints.
Run Code Online (Sandbox Code Playgroud)

但是,如果您不知道需要存储多少个整数,那么您可以这样做

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);
Run Code Online (Sandbox Code Playgroud)

  • 我知道这是旧的,但出于好奇,你不能这样做:int my_table [count]; ?如果是这样,为什么在这个例子中使用malloc? (6认同)

sun*_*oon 9

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