-6

scanf takes a pointer argument.. Why cant we pass a pointer variable?

int* x;
scanf("%d", x);
printf("%d", *x);

This does not give output.. Why? What is wrong?

2
  • 4
    Please read a beginner-level C book. To begin with, you need to initialize the variable... Commented Oct 12, 2017 at 12:07
  • Thank you... A pointer must have a value first...Now it works.. int a = 0; int* x = &a; scanf("%d", x); printf("%d", *x); Commented Oct 12, 2017 at 12:11

1 Answer 1

2

The %d format specifier to scanf expects a pointer to an int, i.e. a int *, which is what you are passing. So you're calling the function correctly.

Where you went wrong is that the pointer x was never initialized and therefore doesn't point anywhere. scanf then attempts to read this unitialized value as an address and subsequently read what is at that bogus address. Reading an uninitialized value invokes undefined behavior.

You need to make x point somewhere, either by assigning it the address of an int variable or by using malloc to dynamically allocate memory.

int a;
int *x = &a;

Or:

int *x = malloc(sizeof(int));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.