memcpy a buffer and an array not working

风格不统一 提交于 2019-12-05 10:44:17
memcpy(a,b,10);

The third argument it the number of bytes to copy. You want memcpy(a, b, 10 * sizeof *a).


Also, you are missing an #include <string.h>, that's why you get the warning.

The memcpy() function usage is the following:

 void * memcpy ( void * destination, const void * source, size_t num );

where num is a number of bytes.

In order to fix this you need to use it the following way:

memcpy(a,b,10*sizeof(int));

Because usually size of an integer is 4 bytes (depending on the platform, compiler, etc).

In your program you copy only 10 bytes instead of 40 bytes. So, in this case you are getting the first "2,5" elements initialized in the array a[] and the rest contains garbage.

EDIT: Also you forgot to #include <string.h>, so this causes the following compilation warning:

array.c:15:2: warning: incompatible implicit declaration of built-in function ‘memcpy’

For the future, please give an attention to the compiler warnings, as it will allow to you to avoid a lot of run-time errors.

Last parameter of memcpy is number of bytes to copy, so it should be memcpy(a,b, 10 * sizeof(int));

You have to include <string.h>

Last param of memcpy is "Number of bytes to copy". (you are passing number of elements)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!