Question

Question related to this: How can I read an input string of unknown length?

Several questions:

What does the line if(!str)return str mean?

Why is int ch an integer? Isn't it supposed to be a char?

What is the purpose of the size given to the function exactly?

Asking in a separate question because I understood the method, just not some of the stuff under the hood.

Was it helpful?

Solution

The line if (!str) return str; basically means if (str == NULL) return NULL; which is just error checking the return value of realloc.

The reason we make ch an int is because the function fgetc returns an int (that is how we can have EOF be returned yet EOF isn't a legal char value).

The size argument simply represents the initial size of the buffer that we allocate. So if the person calling the function has a pretty good (not necessarily exact) idea of how big the string will be, they can give it in this parameter and save a lot of time by avoiding extra calls to realloc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top