Can someone tell me how to use Dynamic Allocation for char array, when I don't have the size of the input upfront?
1 Answer
You have to allocate memory and then reallocate. Here an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
//allocate a buffer of 10 pointers
size_t array_size = 10;
char ** array=(char **)malloc(array_size * sizeof(*array) );
if (!array)
return -1;
//now allocate the 10 pointers with a buffer to hold 42 characters
for (int i = 0; i < array_size; i++) {
array[i]= (char *)malloc( 42 * sizeof (*array[i]) );
if (!array[i])
return -1;
strcpy(array[i], "10");
}
//for some reason we need to increase array size by 1
++array_size;
array = (char **)realloc(array, array_size * sizeof(*array) );
array[array_size-1] = (char *)malloc(42 * sizeof(*array[array_size-1]) );
if (!array[array_size-1])
return -1;
strcpy(array[array_size-1], "12");
}
realloc).