2

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?

1
  • It doesn't output the desired data.... What does it output, and what is desired? Commented Sep 16, 2010 at 19:25

6 Answers 6

12

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

 memcpy(dest,src,5*sizeof(dest[0]))
Sign up to request clarification or add additional context in comments.

1 Comment

5 * sizeof dest[0], or sizeof src, may be preferable.
3

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));

Comments

1

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

Comments

1

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;
}

Comments

1

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) );

1 Comment

Ah! Almost. You were on the right track: where "x" stands for the object. Try memcpy(dest, src, sizeof src);
0

Better is

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.