-1

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.

Community
  • 1
  • 1
Sunspawn
  • 817
  • 1
  • 12
  • 27
  • 2
    `if(!str)` is checking if the allocation failed. – Maroun Dec 22 '13 at 07:14
  • 1
    @H2CO3 We are not going to pollute the question queue with little questions. It is far more efficient and produces higher quality, when small highly related questions are grouped together into one *Question*. – randomusername Dec 22 '13 at 07:31
  • @randomusername Ugh, we're splitting hair here, aren't we? That's cute. Then let's do it in an even better way: what if I told you that this question(tuple) shouldn't have been asked at all? All the explanation of these basic constructs can be found in a decent beginners' tutorial; Stack Overflow is not a "teach me the language by explaining basic programs" site. –  Dec 22 '13 at 07:33
  • 1
    @H2CO3 The OP had a question, they sought out help and thus they should be able to get it. Sure, SO may not be the right place to ask this, so tell us where on the Stack Exchange network we should move this question to. – randomusername Dec 22 '13 at 07:42

1 Answers1

6

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.

randomusername
  • 7,927
  • 23
  • 50