C语言 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的整个列表打印到字符串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()代替。

最新更新