scanf() int and string difference

Hi,

When using scanf(), why do you need the & operator for ints and not for strings?

Thanks

int a;
char s[100];

scanf("%d", &a);  // store an int
scanf("%s", s); // store a string

Because a string is an array. And calling the array (without calling a member of it) will give you the pointer to the first element of that array.

And & is the address operator, it gives the address of the variable you point at. And because a will give you the value of it instead of the address you need the &. But s already gives you the address. It's the same as calling &s[0].

When using scanf(), why do you need the & operator for ints and not for strings?

The & symbol (not operator) tells the compiler to pass by reference. That is, pass the address of a variable, not the contents. The scanf() function needs an address to write to.

Arrays are always passed by reference, to avoid needing to copy every element of an array to the function. So, there is no need to tell the compiler to pass the address of the array, since that it what it does by default.

Thanks folks :slight_smile:

@PaulS, why don't you call it an operator?

Also, I'm taught to call it pass by pointer and call functions like myFun(int &a) pass by reference. Although both pass a reference :p

PaulS: The & symbol (not operator)

K&R refers to it as a unary operator.

AWOL: K&R refers to it as a unary operator.

Yeah, I've had my tea now...