简体   繁体   中英

Expand an non-pointer array

let's say I have an array in C:

char *list[3] = {"Hello", "world", "!"};

And I want to expand it. If I daclare that array as:

char **list = (char **) malloc(3 * sizeof(char *));  // Or sth. like that...

I can resize it:

realloc(list, 5 * sizeof(char *));  // Not sure now if I should use `char *` or `char **`

If I try this:

char *list[3] = {"Hello", "world", "!"};
realloc(list, 5 * sizeof(char *));  // Not sure now if I should use `char *` or `char **`

It says that it can't resize memory that wasn't allocated.
Ok, but how can I then resize an array like this?

You can't. If you have a statically-sized array, you simply can't change its size. If you need to be able to change the size, don't use a statically-sized array.

PS: You should not ignore the return value of realloc . There's no guarantee that realloc is able to grow the given memory chunk, so it may return a pointer to an entirely new chunk of memory (freeing the old memory). So you should always use the pointer returned by realloc and never assume that the old pointer is still valid after calling realloc .

When you're using the following statement:

char *list[3] = {"Hello", "world", "!"};

… the compiler is generating the array for you. But malloc doesn't know about it. You need to allocate with malloc , then copy your static array into the dynamic region. Only then can you change its size with realloc .

char *staticList[3] = {"Hello", "world", "!"};
// Allocate dynamically.
char **list = malloc(sizeof(staticList));
// Copy static array.
memcpy(list, staticList, sizeof(staticList));
// Change size to 5 entries.
list = realloc(list, 5 * sizeof(list[0]));

The simple answer is that you can't. You can either have a fixed-size array, or a dynamically allocated array, but you can't mix them.

The reason for this is that fixed-sized arrays are created by the compiler at the time of compilation 1 . It simply sets aside a bit of the memory used by the program to store the array. If it's a local variable that memory is on the stack, if it's a global variable it's in the global data space. The dynamic allocation function like malloc and realloc allocates from a different pool of memory, and these different pools of memory are not compatible.

1 Variable-length arrays are not allocated by the compiler at the time of compilation, or they would not be variable -length arrays. How the compiler implements them doesn't matter, they are still "fixed-sized" arrays and can not be reallocated once created.

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