0

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

1
  • @xing thank you. That worked properly Commented Apr 8, 2019 at 17:32

1 Answer 1

1

int temp[b]; is local to the function. Once you return from the function, lifetime of that memory ceases and accessing it would yield undefined behaviour.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.