0

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?

1

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

8 Comments

I didn't downvote, but maybe you schould explain that an array is not a pointer and a pointer is not an array and what an array-type looks like.
@Swordfish And how would that be helpful in the context? I explained Arr[i] is not a pointer, and it won;t decay to pointer either. That answers the question, is not it?
I'm concerned about the 2nd sentence of the question and I sense there is a more general confusion with the OP about arrays. But as I said, I didn't donvote and my comments are just my € 0.02.
@Swordfish Right, I get you're trying to help, and I know you'll not be downvoting for that reason. Maybe someone lost their keys. :)
I understood, did some research on that. But can you make it clear what 15 means here in scanf("%15s", array)
|

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.