Alfred James
Alfred James

Reputation: 1019

referencing int in scanf

This question may look stupid but that's how people learn :).I learned C++ where you didn't have to worry about referencing int variable in cin>> . Today I was learning filehandling in C for school work but When I tried to run the program with this syntax, I got error.

scanf("%d\n %s\n",id, name);

But when I referenced id in scanf, the error was gone.i-e;

scanf("%d\n %s\n",&id, name);

Why is this so? I will be very thankful for answering this noob question..

Upvotes: 2

Views: 125

Answers (4)

Murtaza Ali Baig
Murtaza Ali Baig

Reputation: 1

scanf() requires the address of the variable to store the data into.

In case of an integer, the "&" symbol is required to refer to the address of the integer variable. But in case of string it is not required to use "&" as a string is already a pointer to a character array.

Upvotes: 0

john
john

Reputation: 87957

scanf is a C function. C doesn't have references, so to alter a variable scanf needs to be passed a pointer to that variables location. C++ has references so it doesn't need pointers, although it could use them also.

Upvotes: 0

Dipstick
Dipstick

Reputation: 10129

scanf needs the address of id so it scan store the value there. It has no interest in its current value which is what it is given in your first case.

Upvotes: 1

Levon
Levon

Reputation: 143042

scanf is a function that expects a pointer to a variable so that it can store the value it reads into the location pointed to by the pointer.

name is presumably some sort of (char?) array, so the identifier for that variable already refers to an address, so the & operator is not necessary. It is however for the int variable (I'm assuming id is some sort of int) you need to get the address to pass to scanf in the call.

Upvotes: 1

Related Questions