i am facing some problem with a memcpy.

I have a struct. lets us say

{ unsigned in[6] ; //32 bytes in all



  unsigned int a;   
  char b[1020];    
  strb a[512];     //512* 32 = 16384 bytes

Now, ihave a copy of the struct A. Let us call it B.

My goal is to copy all the contents from B to A.

if i do a

memcpy(&A,&B& ,sizeof(A)); 

// This works perfectly well.

But if i do

memcpy( &A,&B,sizeof(A/2));
memcpy( &A+sizeof(A/2), &B+sizeof(B/2),sizeof(A/2));

the contents are not getiing reflected.

Actually the FIRST HALF of A is 16384 bytes and the LAST ENTRY is 16384. Total size is 32768.

I am not able to find out what the problem is .

Can anyone pls point me to what could be wrong?

Many Thanks.

Recommended Answers

All 4 Replies

This is not what you want: sizeof(A/2)

You want sizeof(A)/2

You can't divide the A by 2, that doesn't make sense, right? Move the 2 outside the brackets.

Sorry, i meant


Try using a smaller example. Like

struct {
    char s[5];
} a = { "abcd" }, b = { "mnop" };

memcpy(&a, &b, sizeof(a)/2);
memcpy(&a+2, &b+2, sizeof(a)/2);

printf("%s", a.s);    // should be "mnop"

I tried my code thinking it would work but you have to cast the address to a pointer of the variable or structure.

struct {
    char s[5];
} a = { "abcd" }, b = { "mnop" };

memcpy(&a, &b, sizeof(a)/2);
memcpy((char*)&a+2, (char*)&b+2, sizeof(a)/2);

printf("%s", a.s); // should be "mnop"

So your code should be like

// let's give our structure a name
struct info {
    [variables here]


memcpy(&A, &B, sizeof(A)/2);
memcpy((struct info*)&A+sizeof(A)/2, (struct info*)&B+sizeof(B)/2,sizeof(A)/2);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.