1

I know that arrays decay to pointer. As a result, because it behaves like a pointer, it can essentially be passed to functions with arguments that require a memory address without the use of an ampersand. For instance:

char name[10];
scanf("%s", name);

is correct.

However, let's say if I want to fill in only the first element of 'name' array, why can't I write it as

scanf("%c", name[0]);

but must write it with the ampersand in front of 'name[0]'? Does this mean that individual array elements do not decay to pointers and do not hold their individual memory address as opposed to their entire array counterpart?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
xhxh96
  • 649
  • 1
  • 7
  • 14
  • 3
    How can `name[0]` can decay to pointer if it returns the value of first element of array????... – LPs Jun 23 '16 at 08:20
  • Ah I have never thought of that array elements return values and not memory address and thus not a pointer as an explanation. Thanks! – xhxh96 Jun 23 '16 at 08:22
  • @TruthOrDare Maybe you should take a look at [Array of Pointers](http://ideone.com/OgJtST) – Michi Jun 23 '16 at 08:50

2 Answers2

1

Arrays decay to pointer to the first element when passed as function argument, not array element(s).

Quoting C11, chapter §6.3.2.1/ p3, Lvalues, arrays, and function designators, (emphasis mine)

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.

An array element is not of array type, the array variable is. In other words, an array name is not the same as a(ny) array element, after all.

So, individual array elements do not decay to pointer-to-anything-at-all even if passed as function arguments.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I'm just curious, does `Array` decay to Pointer to its first element or the `Array name` decay to pointer? – Michi Jun 23 '16 at 08:47
1

The problem is that char name[10] can behave as char* name which is ok for scanf which expects second argument to be a pointer (address in memory). But when you write name[0] you are getting the value and not the pointer.

For example if name is "Hello world" then name[0] == 'H'. But scanf wants a pointer. So in order to get name[0]'s address you need to write scanf("%c", &name[0]).