【发布时间】:2021-11-16 10:04:05
【问题描述】:
我一直在阅读 malloc 用于动态内存分配。但是如果下面的代码有效...
int main(void) {
int i, n;
printf("Enter the number of integers: ");
scanf("%d", &n);
// Dynamic allocation of memory?
int int_arr[n];
// Testing
for (int i = 0; i < n; i++) {
int_arr[i] = i * 10;
}
for (int i = 0; i < n; i++) {
printf("%d ", int_arr[i]);
}
printf("\n");
}
... malloc 的意义何在?上面的代码不就是一种更易于阅读的动态分配内存的方式吗?
我在另一个 Stack Overflow 的回答中读到,如果某种标志设置为“pedantic”,那么上面的代码会产生编译错误。但这并不能真正解释为什么 malloc 可能是动态内存分配的更好解决方案。
【问题讨论】:
-
查找
stack和heap的概念;不同类型的记忆有很多微妙之处。 -
提示:编写两个附加函数,
A和B。以这种方式让A“分配”内存并返回指向它的指针。做一些涉及函数调用的其他事情(打印内容,从文件中读取其他内容等等),然后将指针从A传递到B并让B从中读取。看看基于堆栈的分配有多么有用。 -
"I read on another Stack Overflow answer that if some sort of flag is set to "pedantic", then the code above would produce a compile error."-- 它不会在 C 中产生编译器警告/错误,但在 C++ 中会产生,如果您在 ISO 兼容模式下编译(-std=C++20 -pedantic带有 gcc 和 clang 的命令行参数)。这是因为VLAs 是 ISO C 的一部分,而不是 ISO C++。
标签: arrays c memory-management malloc heap-memory