How to use realloc in a function in C

后端 未结 3 1446
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 06:34

Building on what I learned here: Manipulating dynamic array through functions in C.

void test(int data[])
{
    data[0] = 1;    
}    

int main(void)
{    
         


        
3条回答
  •  情深已故
    2020-11-29 06:53

    You want to modify the value of an int* (your array) so need to pass a pointer to it into your increase function:

    void increase(int** data)
    {
        *data = realloc(*data, 5 * sizeof int);
    }
    

    Calling code would then look like:

    int *data = malloc(4 * sizeof *data);
    /* do stuff with data */
    increase(&data);
    /* more stuff */
    free(data);
    

提交回复
热议问题