I want to read a string entered by the user. I don’t know the length of the string. As there are no strings in C I declared a pointer:
char * word;
and used scanf to read input from the keyboard:
scanf("%s" , word) ;
but I got a segmentation fault.
How can I read input from the keyboard in C when the length is unknown ?
You have no storage allocated for
word– it’s just a dangling pointer.Change:
to:
Note that 256 is an arbitrary choice here – the size of this buffer needs to be greater than the largest possible string that you might encounter.
Note also that fgets is a better (safer) option then scanf for reading arbitrary length strings, in that it takes a
sizeargument, which in turn helps to prevent buffer overflows: