Changing C array elements

I define three arrays. As soon as the first one is highlighted, I print out its first element, which is as expected. Then the second array is allocated ("problem"). When I retype the first element of the first array, it magically changes the value that I assigned to the array as "problematic." He's getting weirder. If I decided not to allocate the array as "problematic", but to "work" between the two print statements, everything works fine.

What's happening?

#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;
}
+4
source share
2 answers

This array is not bound, you select 10 elements with index from 0 to 9, but you get access to index 10. Your loop should only be

for (int el=0;el<limit2;el++){problematic[el]=2.;}

_, , . , [10] , big_bounds [0]

+6

valgrind , . init 0.

0

Source: https://habr.com/ru/post/1692065/


All Articles