Returning Array from function in C

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

    The problem is that when sumarrays returns, the total array ceases to exist1, so the pointer value that main receives is no longer valid. In short, you cannot return arrays from a function like this.

    You have several options.

    The first (and IMO the preferred option) is to pass the total array as one of your parameters, and make the caller responsible for setting aside enough memory:

    void sumarrays(int arr1[], size_t arr1len, int arr2[], size_t arr2len, int *total, size_t totallen) 
    {
      ...
      for (i = 0; i < totalLen; i++) {
          total[i] = *(arr1 + i) + *(arr2 + i);
      ...
    }
    
    #define ARRLEN 10
    
    int main( void )
    {
      ... 
      int x[ARRLEN];
      ...
      sumarrays( arr1, ARRLEN, arr2, ARRLEN, x, ARRLEN);
    

    In this method, the caller (main) is responsible for knowing how big the target array needs to be and setting aside the memory for it. The helps decouple the sumarrays function from main because it doesn't have to rely on information that isn't explicitly specified by the parameter list (such as the array sizes). With this approach, you're not limited to arrays of size 10.

    A second option is to declare total such that it doesn't go away after sumarrays exits. You can do this by either declaring it at file scope (as in ryyker's answer), or by declaring it static within the sumarrays function:

    int *sumarrays(int arr1[], size_t arr1len, int arr2[], size_t arr2len) {
        int i;
        static int total[10];
        ...
    

    With this approach, the total array will be allocated at program startup and held until the program terminates. What makes this approach less desireable is that you have only a single instance of that total array, which is shared across all calls to sumarrays. The function is no longer re-entrant; if sumarrays called another function that called sumarrays, then whatever the first call had written to total would be clobbered by the second call (the strtok library function has this problem, which has caused much heartburn in the past). Your code obviously doesn't have this problem, but it's something to be aware of. Don't declare things static if you don't have to.

    The final option is for sumarrays to allocate the memory for total dynamically (as in haccks' and merlin2011's answers). That avoids the re-entrancy issue, but now you have to deal with memory management. C isn't your mother and won't clean up after you, so any memory you allocate with malloc or calloc you have to release with free2.


    1. Logically speaking, anyway; the memory is obviously still there, but it's been made available for the rest of the system to use, and has been overwritten in the time it took for your program to return to the main function.

    2. Most platforms will reclaim dynamically allocated memory when the program exits, but a few (admittedly older, oddball platforms) may not. Also, for long-running programs (servers, daemons, etc.), you have to be very careful to release any memory you allocated and no longer need, otherwise you will eventually run out.

提交回复
热议问题