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
943 views
in Technique[技术] by (71.8m points)

c - memcpy for multidimensional array

Is there a way we can copy every element from one multidimensional array to another multidimensional array by just doing one memcpy operation?

int array1[4][4][4][4];
int array2[4][4][4][4];
int main()
{
    memset(&array1,1,sizeof(array1));
    memset(&array2,0,sizeof(array2));
    printf_all("value in array2 %d 
",array2[1][1][1][1]);
    memcpy(&array2,&array1,sizeof(array2));
    printf("memcopied in array2 from array1 
");
    printf("value in array2 %d 
",array2[1][1][1][1]); //not printing 1
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your code is correct. You should not expect the output to show you a value of 1. You should expect it to show you a value of 16843009, assuming a 4 byte int.

The reason is: you are filling array1 with bytes of value 1, not with ints of value 1. i.e. binary 00000001000000010000000100000001 (0x01010101) is being filled into all the int elements with your memset operation.

So regardless of the size of int on your machine (unless it's a single byte!) you should not expect to see the value 1.

I hope this helps.


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

...