Harsh Bhudolia
Harsh Bhudolia

Reputation: 153

Array Input using for loop

I am a beginner in programming. It was taught that arrays store address of the first element. While using for loop when I input the Array elements using scanf I should not use & character right it should be ("%d",Arr[i]) , instead of ("%d",&Arr[i]) . but why it is showing error?

Upvotes: 0

Views: 255

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Array type has a special property, in some of the cases, a variable with type array decays to a type as pointer to the first element of the array.

Quoting C11, chapter §6.3.2.1

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]

However, if the type is not an array type, it does not hold.

From your description, it sounds you have the array defined as

int Arr[16];   // 16 is arbitrary, just for example

In your case, Arr is an array of integers and Arr[i] is not an array type, it's an integer. So, you have to pass the address of this integer to scanf().

The correct statement would be

 ("%d",&Arr[i]); // passing the address.

To compare, if you have an array defined like

 char array [16]; 

then you can write

 scanf("%15s", array); // 'array' is array type, which is same as `&array[0]` in this case

Upvotes: 3

Related Questions