-1

Why this code compile but not running?

int main() {
     char *s;

     scanf("%15s", s);
     puts(s);
 } 
cleblanc
  • 3,678
  • 1
  • 13
  • 16
Adam
  • 13
  • 4

3 Answers3

2

Because s is an uninitialized pointer, you cannot store data there (since there "is no there there").

Try:

char s[32];

instead, that gives you 32 characters' worth of room into which scanf() can write.

unwind
  • 391,730
  • 64
  • 469
  • 606
2

You need to provide memory for scanf(...) The char *s is only a pointer to some memory, but not he memory itself. You can either malloc(...) the memory and have s point to it, or allocate it locally on the stack by char s[16]

cleblanc
  • 3,678
  • 1
  • 13
  • 16
1

For starters, provide a proper buffer to the scanf call. For example, instead of char *s which is simply an uninitialized pointer, try char s[128].

Phil Brubaker
  • 1,257
  • 3
  • 11
  • 14