我可以反转数组到指针衰减的过程吗?

问题描述:

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

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.