R.O.S.S
R.O.S.S

Reputation: 615

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?

Upvotes: 0

Views: 190

Answers (3)

DarkDust
DarkDust

Reputation: 92316

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]));

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

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 compilation1. 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.

1Variable-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.

Upvotes: 0

sepp2k
sepp2k

Reputation: 370112

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.

Upvotes: 2

Related Questions