tags:

views:

71

answers:

6

Hi guyz,

The following program doesn't output desired data (on VC2008 compiler)

#include <stdio.h>
#include <string.h>

int main(void)
{
    int i;
    int dest[10] = {1};
    int src [] = {2, 3, 4, 5, 6};

    memcpy(dest, src, 5);
    for (i=0; i<10; i++) printf("%i\n", dest[i]);

    return 0;
}

whereas using char arrays instead, every thing goes fine! where is the problem here?

+10  A: 

memcpy takes a number of bytes to copy - not a number of objects.

 memcpy(dest,src,5*sizeof(int))
Martin Beckett
`5 * sizeof dest[0]`, or `sizeof src`, may be preferable.
caf
good idea - i'm showing my ancient C roots !
Martin Beckett
+1  A: 

Try memcpy(dest,scr,sizeof(int)*5)

mcabral
+3  A: 

memcpy copies bytes only. you need to tell it how many bytes to copy by multiplying the number of objects by the size of each object like so:

memcpy(dest, src, 5 * sizeof(int));
quixoto
+1  A: 

You need to add the sizeof(int):

#include <stdio.h>
#include <string.h>

int main(void)
{
    int i;
    int dest[10] = {1};
    int src [] = {2, 3, 4, 5, 6};

    memcpy(dest, src, sizeof(int) * 5);
    for (i=0; i<10; i++) printf("%i\n", dest[i]);

    return 0;
}
paercebal
+1  A: 

You want to call memcpy with a sizeof( x ) where "x" stands for the object. Here you'd do

memcpy( dest, src, 5*sizeof(int) );
wheaties
Ah! Almost. You were on the right track: **where "x" stands for the object.** Try `memcpy(dest, src, sizeof src);`
pmg
A: 

Better is

memcpy( dest, src, 5*sizeof*src) );

If you change array-type to an other type, the code must not changed.