Why doesn't y=x work for arrays?
Why won't the following C code compile? It seems like it should just change the pointers' address but i开发者_开发百科t throws an error.
int x[10];
int y[10];
y=x;
x
and y
are arrays, not pointers. In C, arrays can't change size or location; only their contents can change. You can't assign arrays directly.
If you want a pointer to one of the arrays you can declare one like this.
int *z = x;
If you need to assign an array you can create a struct that contains an array. struct
s are assignable in C.
What pointers? You have two arrays. Arrays are not pointers. Pointers hold the address of a single variable in memory, while arrays are a contiguous collection of elements up to a specified size.
That said, arrays cannot be assigned. Conceivably, saying y = x
could copy every element from x
into y
, but such a thing is dangerous (accidentally do an expensive operation with something as simple looking as an assignment). You can do it manually, though:
for (unsigned i = 0; i < 10; ++i)
y[i] = x[i];
y is statically allocated. You can't change where it points.
Because an array is (has) a pointer value (rvalue) but is not a pointer variable (lvalue).
int a[10];
int *p;
p = a; // OK
a = p; // Compile Error
y is not a "pointer", but a fixed array. You should consider it as a "constant of type int *", so you can't change a constant's value
Regards
精彩评论