1

I've implemented my own dynamic array data structure in c and now i am looking for a way to fill them up without losing their dynamicity.

If i write something like

char str[ANY_CONSTANT];
fgets(str, ANY_CONSTANT, stdin);

The number of elements i can pass to my program is defined at compilation time, which is exactly what i do not want to happen.

If i write something like

char str[ANY_CONSTANT];
scanf("%s", &str)

I have the same situation. Is there any function that i can use to input data from the keyboard without any fixed dimension? Thanks in advance!

terdop
  • 49
  • 6

1 Answers1

2

You can try the POSIX getline function:

char *buf = NULL;
size_t buflen = 0;
ssize_t readlen = getline(&buf, &buflen, stdin);
/* buf points to the allocated buffer containing the input
   buflen specifies the allocated size of the buffer
   readlen specifies the number of bytes actually read */

getline reads an entire line from the console, reallocating the buffer as necessary to store the whole line.

nneonneo
  • 171,345
  • 36
  • 312
  • 383