分配差异

mus*_*tze 3 c arrays malloc pointers

可能重复:
声明和malloc之间的区别

这两个程序有区别吗?

int main(void) {
    char str[80];
}
Run Code Online (Sandbox Code Playgroud)

int main(void) {
    char * str = (char*) malloc( sizeof(char) * 80 );
}
Run Code Online (Sandbox Code Playgroud)

那么使用malloc和类似数组的语法之间有区别吗?所以如果我需要80个字符的内存,我应该使用malloc而不是其他可能性,对吧?

我会试着回答我自己的问题!

sim*_*onc 6

char str[80];
Run Code Online (Sandbox Code Playgroud)

在堆栈上分配80个字节.当str超出范围时,这将自动回收.

char * str = (char*) malloc( sizeof(char) * 80 );
Run Code Online (Sandbox Code Playgroud)

在堆上分配80个字节.在您打电话之前,此内存可用free.

请注意,第二种情况可以简化为

char * str = malloc(80);
Run Code Online (Sandbox Code Playgroud)

即你不应该从mallocC中投出回报,并sizeof(char)保证为1