的memcpy(),我应该尺寸参数的值是什么? [英] memcpy(), what should the value of the size parameter be?

查看:162
本文介绍了的memcpy(),我应该尺寸参数的值是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要一个int数组复制到另一个int数组。它们使用相同的定义长度,因此他们将永远是相同的长度。

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.

有什么利弊/ size参数以下两种选择的利弊memcpy的()?

What are the pros/cons of the following two alternatives of the size parameter to memcpy()?

memcpy(dst, src, ARRAY_LENGTH*sizeof(int));

memcpy(dst, src, sizeof(dst));

请问第二个选项总是工作?不管所述内容的?

Will the second option always work? Regardless of the content?

这有利于最后一个有一件事是,如果阵列要改变,这将是一些看家更新的memcpy()的。

One thing that favors the last one is that if the array were to change, it'll be some house-keeping to update the memcpy()'s.

感谢

推荐答案

只要 DST 被声明为具有大小的数组,的sizeof 将返回以字节数组的大小:

As long as dst is declared as an array with a size, sizeof will return the size of that array in bytes:

int dst[ARRAY_LENGTH];

memcpy( dst, src, sizeof(dst) ); // Good, sizeof(dst) returns sizeof(int) * ARRAY_LENGTH

如果 DST 恰好是一个指向这样一个数组的第一个元素(这是相同类型的数组本身),它不会工作:

If dst just happens to be a pointer to the first element of such an array (which is the same type as the array itself), it wont work:

int buffer[ARRAY_LENGTH];
int* dst = &buffer[0];

memcpy( dst, src, sizeof(dst) ); // Bad, sizeof(dst) returns sizeof(int*)

这篇关于的memcpy(),我应该尺寸参数的值是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆