首页 > 解决方案 > *** 检测到堆栈粉碎 *** 在双倍循环中使用双数组

问题描述

正如标题所说,我用我的代码检测到堆栈粉碎。我无法理解的奇怪之处在于它正确输出了卫星的所有位置,然后堆叠粉碎。当我将限制设置为 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

解决方案


在 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];
    }
}
}

请注意,访问越界的数组会调用未定义的行为。即使存在越界写入,也不需要发生堆栈粉碎检测或分段错误。


推荐阅读