Wcrousse Wcrousse - 1 month ago 6x
C Question

dynamically resizing an array of strings

`I need an array of strings in which the length of the array is not known at compile time. what I've done is:

char **words;
words = malloc(capacity*sizeof(char *));
char nextword[MAX_LEN + 1];

while (true) {
if (num_entries == capacity) {
capacity += 5;
realloc(words, (sizeof(char *) * capacity));
printf("\nEnter a word: ");
fgets (nextword, MAX_LEN, stdin);
if (strlen(nextword) == 0) break;
words[num_entries] = malloc(strlen(nextword + 1));
if (words[num_entries] == NULL) {
printf("\nout of space\n");
strcpy(words[num_entries], nextword);

this seems to work to expand the size once, except that the first element after the expansion has become NULL for some reason. The second time realloc is executed I get an error: "invalid next size".
thanks in advance


Your code is almost there, just need a few modifications. An important thing to remember is that realloc does not modify the value that you pass to it, and it is not required to return the pointer to the same chunk of memory that you passed to it. Here is a working example of using realloc. It is rather straightforward, so you should be able to fix your code by simply following the example.

char **more_words = realloc(words, capacity);
 if (more_words) {
     words = more_words;
 } else {
     // Do something about realloc failure