0

I have a program that repeatedly asks user input a line and stores them in an array. I know how to use dynamic memory allocation to make array if I can get a number of items to store at runtime. for example

char **array = (char**)malloc(numberOfItems * sizeof(char*));

but in my case, I do not know numberOfItems at runtime because I am getting input within a while loop which can be terminated by ctrl+D.

while(!feof(stdin)
{
    array[i] = (char*)malloc(167 * sizeof(char));
}

Any help, please.

Samun
  • 151
  • 1
  • 1
  • 12
  • 1
    You want `realloc`. Lots of examples on the net. – Steve Summit May 22 '18 at 00:02
  • 7
    By the way, if you use `feof()` that way, it's not going to work; see [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – Steve Summit May 22 '18 at 00:05

1 Answers1

1

You can use realloc() to grow the size of memory obtained through malloc(), calloc(), or realloc().

int capacity = 10;
char **array = malloc(capacity* sizeof(char*));

int i = 0;
char line[256];
while(fgets(line, sizeof(line), stdin)) {
    // Resize array when at capacity
    if (i == capacity) {
        capacity *= 2;
        array = realloc(array, capacity * sizeof(char*));
    }

    array[i] = malloc(167 * sizeof(char));
    i++;
}

A few related notes:

Hopefully that is enough to get you started!

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73