Returning Array from function in C

前端 未结 5 412
醉话见心
醉话见心 2021-01-24 14:44

For some reason, my function is only returning the first element in my array and I cannot figure out why the rest of the array goes out of scope. The function takes two integer

5条回答
  •  攒了一身酷
    2021-01-24 15:00

    You are doing stack allocation for your array, and stack-allocated storage goes away when a function returns. Use heap allocation instead.

    Change

    int total[10];

    to

    int* total = malloc(10*sizeof(int)).

    of course, that means you must also free the memory after you are done with it. In this case, before the return 0; in main, you need to

    free(x);
    

提交回复
热议问题