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?

4
  • Yes, you need to allocate memory dynamically. You heard about malloc()? Commented Jan 24, 2020 at 15:45
  • 2
    There are two ways of doing it - easy but non-portable, and hard but portable, with some limitations. Commented Jan 24, 2020 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. man7.org/linux/man-pages/man3/getline.3.html Commented Jan 24, 2020 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? Commented Jan 24, 2020 at 16:54

2 Answers 2

1

consider reading a whole line of input with fgets()

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.