terdop
terdop

Reputation: 49

Issue in filling up dynamic array from keyboard input[C]

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!

Upvotes: 1

Views: 63

Answers (1)

nneonneo
nneonneo

Reputation: 179552

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.

Upvotes: 2

Related Questions