C数组元素值改变

4
我定义了三个数组。一旦分配了第一个数组,我打印出其预期的第一个元素。然后,第二个数组('problematic')被分配。当我重新打印第一个数组的第一个元素时,它神奇地改变为我用数组'problematic'分配的值。情况变得更加奇怪。如果我在两个打印语句之间选择没有分配数组'problematic'而是'working',那么一切都正常运作。
发生了什么?
#include<stdio.h>

int problem(double variable);

int main(){
    problem(1.0);
    return 0;
}

int problem(double variable){

    int limit1 = 10;
    int limit2 = 10;

    double bin_bounds[limit1];
    double problematic[limit2];
    double working[limit2];

    // Allocate first array
    for (int bin=0; bin<limit1; bin++){
        bin_bounds[bin] = variable/limit1 * (bin+1);
    }

    printf("%f\n\n",bin_bounds[0]); // prints 0.2 as excpected
    for (int el=0;el<=limit2;el++){problematic[el]=2.;}
    printf("%f\n\n",bin_bounds[0]); // prints 2.0

    return 0;
}

1
因为您发布了一个 [mcve],所以我点了赞。欢迎来到 StackOverflow。 - TypeIA
3
使用 <= 的 for 循环几乎总是错误的,应该改为 el < limit2 - pm100
2
那个for循环不是在分配第一个数组,而是在填充数组。该数组已经在上面被分配了。 - Christian Gibbons
2个回答

6
这是数组越界,你分配了10个元素,索引从0到9,但你正在访问索引10。你的循环应该只有
for (int el=0;el<limit2;el++){problematic[el]=2.;}

在这种情况下,big_bounds 可能是在 problematic 之后分配的内存。因此,problematic[10] 与 big_bounds[0] 在同一内存地址上。


抱歉,我在这里搞砸了。在原始代码中,循环边界实际上具有相同的值。我已经进行了编辑。 - user6566791
3
@user6566791,没有马卡迪亚人说你需要在你的for循环中将<=改为<.. <=会读取problematic数组的边界之外的1个元素。 - yano
非常感谢 - 那确实是错误。不知何故在涉及相同部分的所有其他函数中都正确地执行了它,然后没有仔细查看有问题的函数。 - user6566791

0

使用valgrind运行并检查是否访问了无效的内存。在声明数组时,将其初始化为0。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接