Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining necessary array length to store input

Tags:

arrays

c

What's the best way to determine the length of an input stream in Stdin so that you can create an array of the correct length to store it using, say, getchar()?

Is there some way of peeking at all the characters in the input stream and using something like:

while((ch = readchar()) != "\n" ) {
    count++;
}

and then creating the array with size count?

like image 661
a3onstorm Avatar asked Nov 26 '25 12:11

a3onstorm


1 Answers

During the time I typed the code, there are several similar answers. I am afraid you will need to do something like:

int  size = 1;
char *input = malloc(size);
int  count = 0;
while((ch = getchar()) != '\n' ) {
    input[count++] = ch;
    if (count >= size) {
         size = size * 2;
         input = realloc(input, size);
    }
}
input[count++] = 0;
input = realloc(input, count);

Alternatively you can use the same as a POSIX library function getline(). I.e.

int count, size;
char *input = NULL;
count = getline(&input, &size, stdin);

In both cases, do not forget to free input once you have finished with it.

like image 191
Marian Avatar answered Nov 29 '25 08:11

Marian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!