Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does scanf() need & operator (address-of) in some cases, and not others? [duplicate]

Why do we need to put a & operator in scanf() for storing values in an integer array but not while storing a string in a char array?

int a[5];
for(i=0;i<5;i++)
scanf("%d",&a[i]);

but

char s[5]; scanf("%s",s);

We need to pass in the address of the place we store the value, since array is a pointer to first element. So in the case with int/float arrays it basically means (a+i).

But whats the case with strings?

like image 414
pranay Avatar asked Aug 09 '10 13:08

pranay


2 Answers

scanf accepts a pointer to whatever you are putting the value in. In the first instance, you are passing a reference to the specific int at position i in your integer array. In the second instance you are passing the entire array in to scanf. In C, arrays and pointers are synonymous and can be used interchangeably (sort of). The variable s is actually a pointer to memory that has contiguous space for 5 characters.

like image 168
Scott M. Avatar answered Nov 18 '22 11:11

Scott M.


When you use the name of an array in an expression (except as the operand of sizeof or the address-of operator &), it will evaluate to the address of the first item in that array -- i.e., a pointer value. That means no & is needed to get the address.

When you use an int (or short, long, char, float, double, etc.) in an expression (again, except as the operand of sizeof or &) it evaluates to the value of that object. To get the address (i.e., a pointer value) you need to use the & to take the address.

like image 3
Jerry Coffin Avatar answered Nov 18 '22 11:11

Jerry Coffin