0

Hello there I was wondering if there is a way in C to ask the user to enter a text, as long as he wants, and use the malloc() function after, according to the characters he has entered.

N. Nik.
  • 1
  • 1
  • where would these characters go, so C could count them afterwards? You need to malloc memory in order to hold the string so you can count it... e.g. it's a chicken/egg problem. – Marc B May 25 '15 at 17:26
  • 2
    To support arbitrarily long input you'd need an unlimited temporary buffer to hold it while you wait for it to end. So the typical solutions are to either limit the length of the input by using a buffer of fixed size, or to read in increments while expanding the buffer (or creating new buffers, e.g., as a linked list). – Arkku May 25 '15 at 17:30
  • No. See [this code that dynamically reallocates a buffer to meet demand](http://stackoverflow.com/a/7832033/2908724). – bishop May 25 '15 at 17:33
  • 1
    If your system supports it: `getline()` does exactly that. Otherwise, use the same prototype and write the function: `ssize_t getline(char **linep, size_t *linecapp, FILE *stream);` – chqrlie May 25 '15 at 18:14
  • Using Standard C, you will need to write a function that allocates space, reads some characters, allocates more space , and so on, in a loop. – M.M May 25 '15 at 21:40

1 Answers1

2

The easiest way to this is probably the m modifier in scanf, which is part of the recent POSIX standard update, and supported in Linux and most recent Unix variants, but not everywhere.

char *string;
scanf("%m[^\n]%*c", &string);

will read a line from stdin (up to and not including a newline, which will be discarded), allocate memory for it with malloc, and store the resulting malloced pointer in the variable string

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226