Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to realloc inner and outer array

So, I got a weird assignment. I have to read a file content to array string. However, I have to initialize the array like this(I have to initialize it as array size 1):

char **input = (char **)malloc(1*sizeof(char*))

instead of

char **input = (char **)malloc((sizeOfFile+1)*sizeof(char*))

So, I have to keep using realloc. My question is, how can I realloc the inner array (the string) and how can I realloc the outher array (the array of string)

like image 626
Nick Stov Avatar asked Feb 17 '23 10:02

Nick Stov


1 Answers

You don't have to reallocate the "inner arrays". The contents of the memory you allocate is the pointers, and when you reallocate input then you only reallocate the input pointer, not the contents of where input points to.


A crude ASCII-image to show how it works:

At first when you allocate a single entry in the input array, it looks like this:

         +----------+    +---------------------------+
input -> | input[0] | -> | What `input[0]` points to |
         +----------+    +---------------------------+

After you reallocate to make place for a second entry (i.e. input = realloc(input, 2 * sizeof(char*));)

         +----------+    +---------------------------+
input -> | input[0] | -> | What `input[0]` points to |
         +----------+    +---------------------------+
         | input[1] | -> | What `input[1]` points to |
         +----------+    +---------------------------+

The contents, i.e. input[0] is still the same as before the reallocation. The only thing that changes is the actual input pointer.

like image 88
Some programmer dude Avatar answered Feb 20 '23 20:02

Some programmer dude