c - *** 检测到堆栈粉碎 *** 在双倍循环中使用双数组
问题描述
正如标题所说,我用我的代码检测到堆栈粉碎。我无法理解的奇怪之处在于它正确输出了卫星的所有位置,然后堆叠粉碎。当我将限制设置为 2 时,它只输出 2 个位置,但不会堆叠粉碎。我尝试增加数组大小以查看是否有帮助,但它根本没有帮助。
这是代码:
#include <stdio.h>
int input[4][3] = {5, 4, 4, -11, -11, -3, 0, 7, 0, -13, 2, 10};
struct Moons
{
int position[2];
int velocity[2];
};
int main()
{
struct Moons moon[3];
for (int i = 0; i < 4; i++)
{
for (int x = 0; x < 3; x++)
{
moon[i].position[x] = input[i][x];
}
}
}
解决方案
在 C 中声明数组时要指定的数字不是最大索引,而是元素的数量。分配足够的元素。
#include <stdio.h>
int input[4][3] = {5, 4, 4, -11, -11, -3, 0, 7, 0, -13, 2, 10};
struct Moons
{
int position[3]; /* increase this */
int velocity[2]; /* not used, but should be increased too? */
};
int main()
{
struct Moons moon[4]; /* increase this */
for (int i = 0; i < 4; i++)
{
for (int x = 0; x < 3; x++)
{
moon[i].position[x] = input[i][x];
}
}
}
请注意,访问越界的数组会调用未定义的行为。即使存在越界写入,也不需要发生堆栈粉碎检测或分段错误。
推荐阅读
- python - 在python中将轮廓点转换为边界框
- javascript - 根据我的函数结果创建一个数组
- vba - 用户关闭表单时如何执行代码?
- python - 在列的总和上使用 pandas 过滤行
- spring - 在运行 mvn spring-boot:build-image 时使用 Artifactory
- firebase - 没有函数的 Firebase 自动 Cron 作业选项
- optaplanner - 在车辆路径问题 (VRP) 中使用 Optaplanner 对车队进行长途旅行规划
- r - 关于 R 中的 prcomp() 的问题。我希望我的国家名称出现在情节上
- ios - 使用 vDSP 对矢量进行去隔行扫描
- javascript - 如何使用相同的函数根据名称将多个项目添加到数组列表中?