-1

I have to read input from the user. I do not know how many lines or how many character per line the user will input, so I can't use an array. If the user inputs an empty line, the input is complete.

My question is, how to do this without the use of arrays. I tried using this code, but it crashes on running.

char *line = "";
gets(line);

Why does this not work? And how can I read the input without the use of arrays?

TIA

Leon van Noord
  • 868
  • 1
  • 7
  • 24
  • 1
    Read about string literal in C.. There are thousands of question in stackoverflow itself. Probably [this](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string) will help you. – Krishnabhadra Apr 29 '13 at 09:44
  • this is a string literal (an empty one), not an array of characters – Marius Bancila Apr 29 '13 at 09:45

1 Answers1

4

That doesn't work because line points at only enough memory to store an empty string, and that memory is typically non-modifiable since string literals cannot be changed at run-time.

You need an actual buffer, like so:

char line[128];

Note that gets() is best avoided, it won't protect against buffer overrun and thus is always going to be dangerous.

Use fgets() instead:

if( fgets(line, sizeof line, stdin) != NULL)
{
  printf("got some input!\n");
}

You say for some reason that you want to do this "without arrays", which is kind of ... hard, since any "buffer" is pretty much an array in C. If you want to avoid using the [] syntax, you need to dynamically allocate the memory instead using malloc().

Then you can't use sizeof like above, it will evaluate to the size of the pointer. Now you need:

const size_t buffer_size = 128;
char *line;

if((line = malloc(buffer_size)) != NULL)
{
    if(fgets(line, buffer_size, stdin) != NULL)
    {
       /* use the data we just read in */
    }
    free(line);  /* discard the buffer so we don't leak memory. */
}
unwind
  • 391,730
  • 64
  • 469
  • 606