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?
-
please read stackoverflow.com/a/1641963/3975177Swordfish– Swordfish2019-05-24 05:51:17 +00:00Commented May 24, 2019 at 5:51
1 Answer
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
sizeofoperator, the_Alignofoperator, 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
8 Comments
Arr[i] is not a pointer, and it won;t decay to pointer either. That answers the question, is not it?