简体   繁体   中英

Why can't I realloc an array that was fully initialized?

Have a look at the piece of code below. When I create an array by malloc ating space for it I can always resize the array without loss of data. But when I create an array by fully initializing it with int test2[] = {3}; I am unable to realloc . Why is that? This is just a silly example but it presents the problem I am facing well.

I tried referencing test2 in different ways (*, &, **, etc) but at some point I found myself just hoping to magically find the solution without knowing what I was doing anymore.

I have been googling a lot but I cannot seem to find a proper explanation for this or solution that works.

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    int *test1 = malloc(1 * sizeof(int));
    test1[0] = 1;
    test1 = realloc(test1, 2 * sizeof(int));
    test1[1] = 2;

    for(int i = 0; i < 2; i++)
    {
        printf("%d\n", test1[i]);
    }

    int test2[] = {3};
    test2 = realloc(test2, 2 * sizeof(int));
    test2[1] = 4;

    for(int i = 0; i < 2; i++)
    {
        printf("%d\n", test2[i]);
    }
}

Output:

test.c: In function 'main':
test.c:17:8: error: assignment to expression with array type
  test2 = realloc(test2, 2 * sizeof(int));

When I remove the code after the first for loop, the program compiles and executes nicely as it should.

The declaration int test2[] = {3}; does not create memory that can be later either freed or re-allocated! Rather, it defines an array of fixed length, most likely 'created' on the stack .

A call to malloc , on the other hand, allocates the requested amount of memory from the heap (essentially, a large pool of memory available to your running program); this memory 'chunk' can later be re-sized with realloc and must be released (when you're done with it) by calling free .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM