How to read string from keyboard using C?

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);

Leave a Comment