2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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);

2 Comments

why do I only need to realloc the str[0]? I think if I want to add size to str[0], while str already full, I have to realloc the whole thing. So, when do I need to realloc str? thx
The str array contains the string pointers - all 100 of them. The individual strings are allocated separately; the pointers to these strings are stored inside str. If you need more than 100 strings, you need to realloc() the str; if you need to increase the length of an individual string, you realloc() a str[i].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.