0

C pointer and string

Is it possible to read in string from stdin and store in a pointer if I didn't know the dimension of the string?

Matteo
  • 1
  • Yes, you need to allocate memory dynamically. You heard about `malloc()`? – RoQuOTriX Jan 24 '20 at 15:45
  • 2
    There are two ways of doing it - [easy but non-portable](https://stackoverflow.com/a/38686325/335858), and hard but portable, with some limitations. – Sergey Kalinichenko Jan 24 '20 at 15:48
  • 2
    Or explicitly call the posix getline() or getdelim() functions which at least means if you build on something other than posix in the future you won't be scratching your head wondering how scanf can be broken. http://man7.org/linux/man-pages/man3/getline.3.html – Gem Taylor Jan 24 '20 at 15:55
  • 1
    Matteo, "if I didn't know the dimension of the string?" --> Do you have a sane upper bound or do you want to allow the user to consume any amount of memory via your code? How about limiting input to a few hundred characters? – chux - Reinstate Monica Jan 24 '20 at 16:54

2 Answers2

1

consider reading a whole line of input with fgets()

C.B.
  • 208
  • 2
  • 7
0

Not only is the ultimate length of input not known at run-time, but the length of chunks of input coming in are not known either. However the answer is yes, it is possible to do what you have asked, but will require dynamic memory allocation using either malloc or calloc AND realloc. Using these functions in conjunction will allow you to capture the input from stdin without knowing beforehand how much there will be.

Refer to the accepted answer to this question for details.

ryyker
  • 22,849
  • 3
  • 43
  • 87