Returning an array using C

前端 未结 8 1093
你的背包
你的背包 2020-11-21 04:45

I am relatively new to C and I need some help with methods dealing with arrays. Coming from Java programming, I am used to being able to say int [] method()in o

相关标签:
8条回答
  • 2020-11-21 05:33

    You can't return arrays from functions in C. You also can't (shouldn't) do this:

    char *returnArray(char array []){
     char returned [10];
     //methods to pull values from array, interpret them, and then create new array
     return &(returned[0]); //is this correct?
    } 
    

    returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.

    You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.

    Option 1:

    dynamically allocate the memory inside of the function (caller responsible for deallocating ret)

    char *foo(int count) {
        char *ret = malloc(count);
        if(!ret)
            return NULL;
    
        for(int i = 0; i < count; ++i) 
            ret[i] = i;
    
        return ret;
    }
    

    Call it like so:

    int main() {
        char *p = foo(10);
        if(p) {
            // do stuff with p
            free(p);
        }
    
        return 0;
    }
    

    Option 2:

    fill a preallocated buffer provided by the caller (caller allocates buf and passes to the function)

    void foo(char *buf, int count) {
        for(int i = 0; i < count; ++i)
            buf[i] = i;
    }
    

    And call it like so:

    int main() {
        char arr[10] = {0};
        foo(arr, 10);
        // No need to deallocate because we allocated 
        // arr with automatic storage duration.
        // If we had dynamically allocated it
        // (i.e. malloc or some variant) then we 
        // would need to call free(arr)
    }
    
    0 讨论(0)
  • 2020-11-21 05:36

    You can use code like this:

    char *MyFunction(some arguments...)
    {
        char *pointer = malloc(size for the new array);
        if (!pointer)
            An error occurred, abort or do something about the error.
        return pointer; // Return address of memory to the caller.
    }
    

    When you do this, the memory should later be freed, by passing the address to free.

    There are other options. A routine might return a pointer to an array (or portion of an array) that is part of some existing structure. The caller might pass an array, and the routine merely writes into the array, rather than allocating space for a new array.

    0 讨论(0)
提交回复
热议问题