将memcpy与数组名称一起使用 [英] Using memcpy with array name

查看:267
本文介绍了将memcpy与数组名称一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C:数组的地址如何等于其值?

我最近在我的项目中找到了调用 memcpy 与数组名称

I recently found code in my project that calls memcpy with the address of array name

int a[10];
memcpy(&a, &b ,sizeof(a));

令人惊讶的(对我来说)似乎工作。

Surprisingly (to me) it seems to work.

应该将其更改为 memcpy(a,b,sizeof(a));

是C ++规范允许的吗?
任何人都可以指向这个行为的资源?是否有任何陷阱?

Is it allowed by the C++ spec? Can anyone point me to resource about this behavior? Are there any pitfalls?

我也检查了

assert((void*)&a == (void*)a);

& a

我在VS2005,VS2008和VS2010中验证了这个行为。

I verified this behavior in VS2005, VS2008 and VS2010.

推荐答案

& a 是数组的地址; a 可以隐式转换为第一个元素的地址。两者都有相同的地址,因此当转换为 void * 时,两者将给出相同的值。

&a is the address of the array; a can be implicitly converted to the address of the first element. Both have the same address, and so both will give the same value when converted to void*.


有没有陷阱?

Are there any pitfalls?

memcpy ,所以它很容易编写代码编译,但行为不好;例如,如果 a 是一个指针而不是一个数组,那么 sizeof a 将会编译但给出错误的值。 C ++的类型安全模板可以防止:

memcpy is not typesafe, so it's quite easy to write code that compiles but behaves badly; for example, if a were a pointer rather than an array, then sizeof a would compile but give the wrong value. C++'s typesafe templates can protect against that:

std::copy(b, std::end(b), a); // will only compile if `b` has a known end.

这篇关于将memcpy与数组名称一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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