memcpy() in Codewarrior EWL

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 
已解决

memcpy() in Codewarrior EWL

跳至解决方案
1,749 次查看
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

标签 (1)
0 项奖励
回复
1 解答
1,145 次查看
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 项奖励
回复
2 回复数
1,146 次查看
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 项奖励
回复
1,145 次查看
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 项奖励
回复