Search code examples
c++memcpy

Memcpy from an array is only working 1/20 instances correctly?


I am coping an item to an array of structures... then copy that element from the array of structures to a char array... but only every 1/20 is working ??

typedef struct{
    double dTime;
    char cMessage[11];
} typeCanMessage;

typeCanMessage *m_cmMessageCB = new typeCanMessage[1000]; //max size can be the CB


memcpy(m_cmMessageCB + *m_posWrite * sizeof(typeCanMessage), &m_cmMessageWrite, sizeof(typeCanMessage));


// WORKS
//memcpy(cStr, &m_cmMessageWrite.cMessage, 11);             

// FAILS: every 1/20 works
memcpy(cStr, m_cmMessageCB->cMessage + *m_posWrite * sizeof(typeCanMessage), 11); 

Solution

  • Pointer arithmetic scales the number by the size of the type of the pointer. m_cmMessageCB->cMessage is a char* pointer, and sizeof(char) is one by definition, so multiplying it by the size of the structure should give the right value. On the other hand m_cmMessageCB + *m_posWrite will already multiply *m_posWrite by sizeof(typeCanMessage), so doing it again will throw off the calculation entirely. I'm surprised it's even working once in every 20 times.