memcpy() in Codewarrior EWL

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

memcpy() in Codewarrior EWL

Jump to solution
1,886 Views
Schwac
Contributor II

Hello all, I have a question regaarding the standard function in cstring.h called memcpy. My issue is that this function should be of the form:

 

void *memcpy(void *str1, const void *str2, size_t n);


When I try to call it in the form:

unsigned int dst[10];

unsigned int src[100];


memcpy(&dst[4], &src[9], 5);


it only copies 1 byte, because that is the length of "5".  I want it to copy 5 bytes. I tried casting the constant 5 to type "size_t":


memcpy(&dst[4], &src[9], ((size_t)5));


This also didn't work.


The way it does work, (although not the way i intended) is:


memcpy(&dst[0], &src[9], sizeof(dst));


How do I use a integer constant or variable in the quantity of bytes field!?

PS: I am using a Coldfire MCF52259.


Thank You,


Cory

Labels (1)
0 Kudos
Reply
1 Solution
1,282 Views
trytohelp
NXP Employee
NXP Employee

Hello,

I performed some tests on my side and checked the Ansi C rules.

The 3rd parameter is the "Number of bytes to copy".

It seems by default it's defined as char type.

If you're using tab defined as char type it will work fine:

      unsigned char dst[10];

      unsigned char src[100];

      memcpy(&dst[4], &src[9], 5);

for your example the tab is using int type (right way).

You must specified the size of int for instance:

      memcpy (&dst[4], &src[9], 5*sizeof(int));

or

      memcpy (&dst[4], &src[9], 20);

Regards

Pascal

View solution in original post

0 Kudos
Reply
2 Replies
1,283 Views
trytohelp
NXP Employee
NXP Employee

Hello,

I performed some tests on my side and checked the Ansi C rules.

The 3rd parameter is the "Number of bytes to copy".

It seems by default it's defined as char type.

If you're using tab defined as char type it will work fine:

      unsigned char dst[10];

      unsigned char src[100];

      memcpy(&dst[4], &src[9], 5);

for your example the tab is using int type (right way).

You must specified the size of int for instance:

      memcpy (&dst[4], &src[9], 5*sizeof(int));

or

      memcpy (&dst[4], &src[9], 20);

Regards

Pascal

0 Kudos
Reply
1,282 Views
Schwac
Contributor II

That is definitely it! Using sizeof() on a data type will return the proper result. This is confusing because all of the PC based examples I was seeing used a constant in this field directly, which doesn't work. memcpy (&dst[4], &src[9], 20); does not work for me on the coldfire or in tests I did using MinGW and G++ compiler. Thank you So Much!

0 Kudos
Reply