Reputation: 669
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?
Upvotes: 1
Views: 91
Reputation: 134376
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.
Upvotes: 1
Reputation: 85
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])
.
Upvotes: 1