How to read string from keyboard using C?

mainajaved picture mainajaved · Oct 10, 2011 · Viewed 276.3k times · Source

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 ?

Answer

Paul R picture Paul R · Oct 10, 2011

You have no storage allocated for word - it's just a dangling pointer.

Change:

char * word;

to:

char word[256];

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 size argument, which in turn helps to prevent buffer overflows:

 fgets(word, sizeof(word), stdin);