Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using scanf function with pointers to character

Tags:

c

scanf

I have written the following piece of code:

int main() {
  char arrays[12];
  char *pointers;
  scanf("%s", arrays);
  scanf("%s", pointers);
  printf("%s", arrays);
  printf("%s", pointers);
  return 0;
}

Why does it give an error when I write scanf("%s", pointers)?

like image 684
Saurabh.V Avatar asked Jan 27 '13 09:01

Saurabh.V


2 Answers

char *pointers;

must be initialized. You can not scan string into pointers until you point it to some address. The computer needs to know where to store the value it reads from the keyboard.

int main() {
  char arrays[12];
  char *pointers = arrays;
  scanf("%s", pointers);
  printf("%s", pointers);
  return 0;
}
like image 54
Junior Fasco Avatar answered Sep 18 '22 15:09

Junior Fasco


  • char *pointers; creates a pointer variable.
  • pointers is the address pointed to by pointers, which is indeterminate by default.
  • *pointers is the data in the address pointed to by pointers, which you cannot do until address is assigned.

Just do this.

char arrays[12];
char *pointers;
pointers = arrays;
scanf("%s",pointers);
like image 29
ATOzTOA Avatar answered Sep 20 '22 15:09

ATOzTOA