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. */
}