Reputation: 57
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?
Upvotes: 2
Views: 6081
Reputation: 726509
No, you do not need to reallocate the array of strings to lengthen the string at index zero. All you need is
str[0] = (char*)realloc(str[0],sizeof(char)*8);
Upvotes: 3
Reputation: 179392
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.
Upvotes: 3