How to overlap internal and external array

So, I have a strange task. I have to read the contents of the file for the array string. However, I have to initialize the array like this (I have to initialize it as the size of array 1):

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

instead

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

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

+4
source share
2 answers

You do not need to redistribute the "internal arrays". The contents of the allocated memory is a pointer, and when you redistribute input , then you redistribute the input pointer, not the contents where input points.


A rough ASCII image to show how it works:

First, when you select one entry in the input array, it looks like this:

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

After redistributing the space for the second record (i.e. input = realloc(input, 2 * sizeof(char*)); )

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

Content i.e. input[0] , remains the same as before redistribution. The only thing that changes is the actual input pointer.

+7
source

Your char** (i.e. a pointer to char ) is an array of pointers pointing to some memory. Therefore, you do not need to allocate memory for a set of char* pointers, but you also need to allocate the memory that each of these pointers point to (the memory in which some characters will be stored):

 const int ARR_SIZE = 10; const int STR_SIZE = 20; char** strArr = malloc(ARR_SIZE * sizeof(char*)); for (int i = 0; i < ARR_SIZE; ++i) strArr[i] = malloc(STR_SIZE * sizeof(char)); strArr[9] = "Hello"; strArr = realloc(strArr, (ARR_SIZE + 5) * sizeof(char*)); for (int i = 0; i < 5; ++i) strArr[ARR_SIZE + i] = malloc(STR_SIZE * sizeof(char)); strArr[14] = "world!"; printf("%s %s", strArr[9], strArr[14]); 

Full example here . Hope this helps :)

+1
source

All Articles