Returning Array from function in C

前端 未结 5 408
醉话见心
醉话见心 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:01

    I agree with every other answer regarding automatic (stack) and heap memory. All good approaches, however global variables on the stack are also an option. It is important to note that it was not that you chose to use stack memory, but that it was also local in scope. Locally scoped automatic variables die when the function that created them returns. However, globally scoped variables, also stored using stack memory, live for the duration of your program, and therefore provide an alternative approach to solve your problem...

    A one line change will result in your code running, change your local copy of total (automatic scope) to a global:

    int total[10];//Put this here,  outside of any function block in same file, i.e. (will give it global scope)
    //note, commented this in function below
    
    int *sumarrays(int arr1[], size_t arr1len, int arr2[], size_t arr2len) {
        int i;
        //int total[10];//move this to global scope
    
    
        for (i = 0; i < 10; i++) {
            total[i] = *(arr1 + i) + *(arr2 + i);
    
        }
        for (i = 0; i < 10; i++) {
            printf("%d\t", total[i]);
        }
    
        printf("\n");
        return total;
    }
    

    With this approach, global scope of variable allows your return to be successful. The array total keeps it's existence on stack until program exits.

提交回复
热议问题