memcpy() from smaller array to larger one

孤者浪人 提交于 2020-01-16 06:59:28

问题


I couldn't find any reference to this question. I have an array of structs which I need to resize into a larger array. both structs are completely initialized (each cell has a value other than NULL)

say

typedef struct Square {
...
...
}Square;

Square s1[1024];
Square s2[2048];

If I copy using memcpy() s1 into s2, how would s2 would look? I know it copies byte data. will the first 1024 cells would be the same as s1 and the remaining 1024 would be as they initialized? or does it affect them too?

Thanks

P.S The arrays here are statically allocated, but I wrote that just for convinience here. I have them allocated using malloc()


回答1:


If you did:

memcpy(s2, s1, sizeof(s1));

The first 1024 Squares in s2 would be copied from s1, and the rest would be untouched (so if they were uninitialized, they'll still be uninitialized).

Remember that if they're heap allocated as you say, you can't use sizeof. You might find realloc useful if all you're trying to do is grow the array.



来源:https://stackoverflow.com/questions/11786970/memcpy-from-smaller-array-to-larger-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!