I wrote a small code to that takes an array of 10 values, passes the array to a function which doubles each value. The array prints expected values (double) within the function. Back in the main function, the output printed has garbage values for index 1, 2 and 3 in the for loop meant to print all values. Why are these values altered? The address is the same in both main and called functions.
StructA doubleArray(int* alist, int b) {
StructA doubled;
int temp[b];
for(int i=0; i < b; i++){
temp[i] = 2 * alist[i];
}
doubled.a = temp;
doubled.b = b;
return doubled;
}
int main() {
int arange[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = 10;
StructA hasDoubledValues = doubleArray(arange, len);
printf("\nvalues in main :");
for(int k = 0; k < hasDoubledValues.b; k++){
printf(" %d \n", hasDoubledValues.a[k]);
}
return 0;
}
its printing values as : 0 0 -14334592 32507 8 10 12 14 16 18
I expected the values to be : 0 2 4 6 8 10 12 14 16 18