c - 在堆栈上声明内存会覆盖之前声明的内存
问题描述
如何在堆栈上分配内存并让它指向不同的内存地址以便我以后可以使用它?例如。这段代码:
for (int i = 0; i < 5; i++) {
int nums[5];
nums[0] = 1;
printf("%p\n", &nums[0]);
}
每次都会打印出相同的地址。如何将内存写入堆栈(不是堆,没有 malloc),并且不会覆盖堆栈上的其他内容。
解决方案
您可以使用alloca
从运行时堆栈中为循环中的每次迭代分配不同的数组。数组内容将保持有效,直到您退出函数:
#include <stdlib.h>
#include <stdio.h>
void function() {
for (int i = 0; i < 5; i++) {
int *nums = alloca(5 * sizeof(*nums));
nums[0] = 1;
printf("%p\n", (void *)nums);
/* store the value of `num` so the array can be used elsewhere.
* the arrays must only be used before `function` returns to its caller.
*/
...
}
/* no need to free the arrays */
}
但是请注意,这alloca()
不是 C 标准的一部分,并且可能不适用于所有架构。关于如何使用它还有进一步的限制,请参阅您系统的文档。
推荐阅读
- arduino - 我想使用入口门自动关闭灯来实现家庭自动化
- python - 我可以为 Python 中的 SVR 代码中的这个错误做些什么
- python - Python curve_fit 不适合正确的罪
- flutter - Flutter 通过 Gesture Detection Details 来降低 Stack 小部件
- python - 我的 while 循环执行但输出不是预期的。为什么?
- python - 使用 TCP 协议发送拆分消息
- javascript - moment.tz.guess 没有显示正确的值
- probability - 如何使用抛硬币进行骰子分配?
- networking - 如何使用 NS3 模拟异构无线网络?
- python - 从列字段中删除星号以绘制