Why won't the following C code compile? It seems like it should just change the pointers address but it throws an error.
int x[10];
int y[10];
y=x;
Why won't the following C code compile? It seems like it should just change the pointers address but it throws an error.
int x[10];
int y[10];
y=x;
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];
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.
y is statically allocated. You can't change where it points.
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