开发者

Why doesn't y=x work for arrays?

开发者 https://www.devze.com 2022-12-23 07:18 出处:网络
Why won\'t the following C code compile? It seems like it should just change the pointers\' address but i开发者_开发百科t throws an error.

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. structs 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

0

精彩评论

暂无评论...
验证码 换一张
取 消