我可以反转数组到指针衰减的过程吗? [英] Can I reverse the process of array-to-pointer decay?

查看:163
本文介绍了我可以反转数组到指针衰减的过程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将指向数组的第一个元素的指针转换为指向整个数组的指针是否合法吗?

Is it legal to cast a pointer to the first element of an array to a pointer to the entire array?

template<typename T, size_t N>
void whatever(T(&)[N])
{
    std::cout << N << '\n';
}

int main()
{
    int a[10];
    int * p = a;
    whatever(*(int(*)[10])(p));   // <-- legal?
}

这在我的编译器上打印10,但我不知道C ++标准允许它。

This prints 10 on my compiler, but I'm not sure if the C++ standard allows it.

推荐答案

不,它不合法(因为它是未定义的行为)。指向整个数组的指针是& a 而不是 p 。基本上,你把一个指针投射到另一个。该标准描述了所有允许的转化,这一个不在其中。

No, it's not legal(as in it's Undefined Behavior). A pointer to the whole array is &a not p. Basically, you're casting one pointer to another. The standard describes all the allowed conversions and this one is not among them.

这篇关于我可以反转数组到指针衰减的过程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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