memcpy()移动结构数组的内容
我正在尝试移动结构数组的内容。
#include<stdio.h>
#include<string.h>
typedef struct {
char texts[1024];
}text_i;
text_i textlist[5];
int main()
{
int ind;
strcpy( textlist[0].texts, "hello ..");
strcpy( textlist[1].texts, "world ..");
printf("texts before memcpyn");
for (ind = 0; ind < 5 ; ind++)
printf("texts ind(%d) is %s n", ind, textlist[ind].texts);
memcpy( &textlist[1], &textlist[0], 4 * sizeof(text_i));
printf("texts after memcpyn");
for (ind = 0; ind < 5 ; ind++)
printf("texts ind(%d) is %s n", ind, textlist[ind].texts);
}
这会将 5 的整个列表打印texts到 string hello ..。
texts before memcpy
texts ind(0) is hello ..
texts ind(1) is world ..
texts ind(2) is
texts ind(3) is
texts ind(4) is
texts after memcpy
texts ind(0) is hello ..
texts ind(1) is hello ..
texts ind(2) is hello ..
texts ind(3) is hello ..
texts ind(4) is hello ..
我的意图是将 textlist[0] 移动到 textlist[1] , textlist[1] 到 textlist[2] , textlist[2] 到 textlist[3] 等等。
预期的:
texts ind(0) is hello ..
texts ind(1) is hello ..
texts ind(2) is world ..
texts ind(3) is
texts ind(4) is
我不想ind(3)和ind(4)不被感动。用上面的格式可以做什么?
回答
使用memcpy()在重叠区域之间进行复制会调用未定义的行为。使用memmove()来代替。