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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

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
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 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 May 24 '19 at 06:19
  • @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? – Sourav Ghosh May 24 '19 at 06:56
  • 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 May 24 '19 at 07:07
  • @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. :) – Sourav Ghosh May 24 '19 at 11:33
  • I understood, did some research on that. But can you make it clear what 15 means here in scanf("%15s", array) – Harsh Bhudolia May 25 '19 at 06:04
  • @HarshBhudolia it indicates the size to be scanned, here its number of elements -1, the last one reserved for null characters. – Sourav Ghosh May 25 '19 at 06:11
  • Just to make sure, Doesn't %s already discard the null character while reading? – Harsh Bhudolia May 31 '19 at 16:10
  • I am new to StackOverflow so I might have ignored the procedures, as I am still acquainting myself with the various working of the site – Harsh Bhudolia Jun 01 '19 at 06:44