tags:

views:

118

answers:

4

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;
+7  A: 

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];
GMan
+9  A: 

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. structs are assignable in C.

Charles Bailey
In the past I've used C compilers that allowed you to change array pointers. It's nice to see it is now verboten. Gives me hope.
T.E.D.
+4  A: 

y is statically allocated. You can't change where it points.

ahmadabdolkader
A: 

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

Giuseppe Guerrini
I like the way you think of an array!
Bryan
caf
Giuseppe Guerrini