Franc
Franc

Reputation: 450

memcpy() to move the contents of an array of structures

I am trying to move the contents of an array of structures.


#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 memcpy\n");
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 memcpy\n");
for (ind = 0; ind < 5 ; ind++)
        printf("texts ind(%d) is %s \n", ind, textlist[ind].texts);
}


This prints the whole list of 5 texts to the 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 ..


My intention was to move the textlist[0] to textlist[1] , textlist[1] to textlist[2] , textlist[2] to textlist[3] and so on.

expected:

texts ind(0) is hello ..
texts ind(1) is hello ..
texts ind(2) is world ..
texts ind(3) is 
texts ind(4) is 

I dont want ind(3) and ind(4) not to be touched. What could be done get it in the above format?

Upvotes: 0

Views: 107

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Using memcpy() to copy between overwrapped regions invokes undefined behavior. Use memmove() instead.

Upvotes: 6

Related Questions