Reputation: 433
In a document by Nick Parlante, it says, Array names are constant i.e array base address behaves like a const pointer.
e.g
{
int array[100], i;
array = NULL; //cannot change base address
array = &i; // not possible
}
But at the same time why is this valid:
void foo(int arrayparm[]){
arrayparm = NULL; // says it changes the local pointer
}
Upvotes: 2
Views: 169
Reputation: 122439
Array types are not assignable in C. It was just a design decision. (It is possible to make assignment of array types copy one array over another, like assignment of structs. They just chose not to do this.)
The C99 standard, 6.5.16 paragraph 2:
An assignment operator shall have a modifiable lvalue as its left operand.
C99 standard, 6.3.2.1 paragraph 1:
... A modifiable lvalue is an lvalue that does not have array type, ...
Plus, even if array types were assignable, NULL
is not a value of type int[100]
.
Upvotes: 0
Reputation: 122383
When array names are passed as function argument, it "decays" to a pointer. So you can treat it like a normal pointer.
Reference: C FAQ what is meant by the ``equivalence of pointers and arrays'' in C?
Upvotes: 1
Reputation: 22821
Arrays decay into pointers in functions. The array name is a non-modifable lvalue
. What this means is that, you can do this:
int x=10,y=20;
int *p = &x; // <---- p Now points to x
p = &y; // <---- p Now points to y
But not this:
int arr[10], x=10;
arr = &x; // <----- Error - Array name is a non-modifiable lvalue.
Since arrays decay immediately into pointers, an array is never actually passed to a function. As a convenience, any parameter declarations which "look like" arrays, e.g.
f(a)
char a[];
are treated by the compiler as if they were pointers, since that is what the function will receive if an array is passed:
f(a)
char *a;
This conversion holds only within function formal parameter declarations, nowhere else. If this conversion bothers you, avoid it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call and/or the uses within the function.
References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226;
Upvotes: 2
Reputation: 58271
Function parameter declarations are different then formal declaration is C, in function declaration:
void foo(int arrayparm[])
^^^^^^^^^ is pointer not array
arrayparm
is pointer but not array its type is int*
. This is equivalent to:
void foo(int *arrayparm)
In function foo
you can modify arrayparm
.
Whereas in formal declaration(in side function) e.g.
int array[100];
array
is not a pointer but it is a constant, It is type is char[100]
and it is not modifiable lvalue.
Upvotes: 3