Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c - Why can't arrays of same type and size be assigned?

If I declare two arrays - arr1 and arr2 - of, say, type int of size 10 each, and initialize first array, and I wish to create a copy of arr1 in arr2; why can't I just give the instruction arr2 = arr1 ?

I know two structures of same type can be assigned. Why is that not the case with arrays?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem with arrays is that in all expressions (except when passed to the sizeof and the unary & operators) they convert to a pointer to their first element.

So, supposing you have:

int arr1[10];
int arr2[10];
...

Then if you write something like

arr1 = arr2;

you are actually attempting to do this:

arr1 = &arr2[0];

or this:

&arr1[0] = &arr2[0];

In both cases you have a problem preventing your code from compiling. In the former case you're attempting to assign between two incompatible types (array vs pointer), while in the latter case you're attempting to modify a constant pointer (&arr1[0]).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...