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

前端 未结 12 2190
灰色年华
灰色年华 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:11

    If you have allocated using malloc you must state the size of the array

    int * src = malloc(ARRAY_LENGTH*sizeof(*src));
    int * dst1 = malloc(ARRAY_LENGTH*sizeof(*dst));
    memcpy(dst1,src,ARRAY_LENGTH*sizeof(*dst));
    

    If you have allocated with a static array you can just use sizeof

    int dst2[ARRAY_LENGTH];
    memcpy(dst2,src,sizeof(dst2));
    

提交回复
热议问题