user6566791
user6566791

Reputation: 75

C array elements change value

I define three arrays. Once the first one is allocated, I print out its first element which is as expected. Then, a second array ('problematic') is allocated. When I reprint the first array's first element, it has magically changed to the value I allocated the array 'problematic' with. It gets even weirder. Had I chosen not to allocate the array 'problematic' but 'working' between the two print statements, everything works fine.

What's going on?

#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;
}

Upvotes: 4

Views: 160

Answers (2)

Rohit
Rohit

Reputation: 152

Run with valgrind and check whether you are accesing invalid memory.During declaring array init it with 0.

Upvotes: 0

marcadian
marcadian

Reputation: 2618

It's array out of bound, you are allocating 10 elements with index 0 to 9 but you're accessing index 10. Your loop should only be

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

The big_bounds is probably allocated right after the problematic in this case. So problematic[10] is at the same memory address as big_bounds[0]

Upvotes: 6

Related Questions