首页 > 解决方案 > How to properly allocate memory for an array pointer passed as an argument in C

问题描述

I am mixed up on my pointers and references. I want to create a pointer in a main function and set it to null. I would like to pass that pointer to another function that creates an array on the heap, fills it, and returns the size of the created array.

I tried to find another article about this topic but failed to find one that allocated memory from within the function. The example code below illustrates the concept but I am not writing a program to accomplish any specific task.

int fillarray(/* pointer to an array */){

    // malloc the array to size n
    // fill array with n elements

return n;
}

int main(){

    int* array = NULL;
    int size = fillarray(/* pass the pointer by reference */);

    for(int i = 0; i < size; i++) printf("%d\n", array[i]);

    free(array);

return 0;
}

UPDATE:

Thank you all for your comments. I learned a ton about pointers working through this problem. The code below accomplishes what I need it to. Thank you @Lundin. Your answer led me to the actual solution. Thank you @ssd as well. Your visual helped me gain some intuition on what I was looking at in the code.

int fillarray(int** array){

    *array = (int*)malloc(2 * sizeof(int));
    (*array)[0] = 0;
    (*array)[1] = 1;

return 2;
}

int main(){

    int* array = NULL;
    int size = fillarray(&array);
    for(int i = 0; i < size; i++) printf("%d\t", array[i]);

return 0;
}

标签: cpointersreferenceheap-memory

解决方案


Strictly speaking there are no "references" in C, everything is passed by value. Although the term "pass by reference" is language agnostic and really just means pass an address to the data. (C++ has a language concept called references, but it's really just glorified read-only pointers.)

So to achieve what you want, you have to pass the address of the pointer itself. That way, the function can access the pointer and set it to point at a new address. Thus declare the function as int fillarray (int**)call the function as fillarray(&array). The result of malloc needs to be assigned to where the pointer-to-pointer points at - it points at the address of the original pointer declared variable in main().

As for allocating a variable size, you will have to add an additional plain integer parameter to the function for that.


推荐阅读