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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With