memcpy(), what should the value of the size parameter be?

前端 未结 12 2158
灰色年华
灰色年华 2020-12-09 09:36

I want to copy an int array to another int array. They use the same define for length so they\'ll always be of the same length.

What are the pros/cons of the followi

12条回答
  •  既然无缘
    2020-12-09 10:06

    If dst was allocated from the heap (using malloc for example) the second solution will not work. sizeof(dst) will only work when it is know to the compiler. For example, the following example will fail as sizeof(dst) will be equal to the sizeof a pointer (4-8 bytes.)

    #define ARRAY_LENGTH 10
    int *dst;
    
    dst = malloc(ARRAY_LENGTH*sizeof(int));
    memcpy(dst, src, sizeof(dst)); // sizeof dst in this case would be 4 bytes on 32 bit system
    

    This code segment will work every time:

    #define ARRAY_LENGTH 10
    int *dst;
    
    dst = malloc(ARRAY_LENGTH*sizeof(int));
    memcpy(dst, src, ARRAY_LENGTH*sizeof(int)); // sizeof would be 40 bytes
    

提交回复
热议问题