memcpy(),size 参数的值应该是多少? [英] memcpy(), what should the value of the size parameter be?

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

问题描述

我想将一个 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.

memcpy() 的 size 参数的以下两种替代方案的优缺点是什么?

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(),size 参数的值应该是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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