Currently, I have some confusion in realloc an array string. If I have this:
char** str = (char**)malloc(100*sizeof(char*));
str[0] = (char*)malloc(sizeof(char)*7); //allocate a space for string size 7
//some other code that make the array full
My question is, if I want to realloc str[0]
to size 8
, do I need to realloc both str
and str[0]
like this:
str = (char**)realloc(str,sizeof(char*)*101);
str[0] = (char*)realloc(str[0],sizeof(char)*8);
Is this correct?
You realloc
the master array when you want to add a string (changing the number of strings). You realloc
an individual string when you want to change that string's length.
Therefore, only realloc
str[0]
if you want to change the string's buffer size.