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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5497728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:14:13  来源:igfitidea点击:

When should I use malloc in C?

cmalloc

提问by kevin

Possible Duplicate:
When should I use malloc in C and when don't I?

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

Hi, I'm new to the C language and found the malloc function. When should I use it? In my job, some say you have to use malloc in this case but other say you don't need to use it in this case. So my question is: When should I use malloc ?It may be a stupid question for you, but for a programmer who is new to C, it's confusing!

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

回答by Makis

With malloc() you can allocate memory "on-the-fly". This is useful if you don't know beforehand how much memory you need for something.

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

If you do know, you can make a static allocation like

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

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

If you however don't know how many ints you need to store, you would do

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

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);

回答by sunmoon

one Primary usage is, when you are working on a list of items and size of the list is unknown to you.

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