memcpy() in Codewarrior EWL

キャンセル
次の結果を表示 
表示  限定  | 次の代わりに検索 
もしかして: 

memcpy() in Codewarrior EWL

ソリューションへジャンプ
1,889件の閲覧回数
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,285件の閲覧回数
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,286件の閲覧回数
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,285件の閲覧回数
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 件の賞賛
返信