Saurabh.V
Saurabh.V

Reputation: 320

using scanf function with pointers to character

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

Upvotes: 17

Views: 89316

Answers (6)

Junior Fasco
Junior Fasco

Reputation: 227

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

Upvotes: 16

autistic
autistic

Reputation: 15632

pointers is being used without initialisation, like int x; printf("%d\n", x);. You need to make your pointer point to something before using it. Which book are you reading?

Upvotes: 3

Gigi
Gigi

Reputation: 29421

Because you're writing to an address in memory that has not been initialized. Writing to memory pointer by an uninitialized pointer invokes undefined behaviour. Either allocate enough memory:

pointers = malloc(256);
if(!pointers)
  perror("malloc");
else
  scanf("%255s", pointers);

Or declare it as a static array:

char pointers[256];

You should also consider using fgets() instead of scanf().

You may want to read i you are interested in fgets():

Difference between scanf() and fgets()

Upvotes: 10

ATOzTOA
ATOzTOA

Reputation: 35950

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

Upvotes: 5

thepratt
thepratt

Reputation: 323

Could you elaborate on the error, i'm not around a compiler right now.

But for scanf and printf to work you must have this at the top of your program:

#include <stdio.h>
#include <stdlib.h>

Both are standard libraries for C. IO contains scanf, I'm fairly sure printf is in the same. But until you know which libraries you need for which functions it doesn't hurt to include both standard libraries for every program. Try to use custom header files as well so you don't need mass #includes for every file.

Don't forget malloc statements for memory allocation.

But I'm unsure what you're attempting to do with your code, please elaborate?

Upvotes: 0

md5
md5

Reputation: 23699

pointers is an unitialized pointer. You are not able to write into it. You shall allocate enough memory to store a string, as you did with arrays. With a pointer, it is possible to use dynamic allocation (cf. malloc).

Upvotes: 1

Related Questions