gpt4 book ai didi

c++ - 在 C++ 中(不在 C 中)具有未指定边界的数组指针的可用情况

转载 作者:IT老高 更新时间:2023-10-28 12:39:46 26 4
gpt4 key购买 nike

考虑以下代码:

int main() {
int (*p)[]; // pointer to array with unspecified bounds

int a[] = {1};
int b[] = {1,2};

p = &a; // works in C but not in C++
p = &b; // works in C but not in C++

return 0;
}

在纯 C 中,您可以将指针分配给任何维度数组的这种类型的地址。但是在 C++ 中你不能。我发现编译器允许为此类指针赋值的一种情况:

struct C
{
static int v[];
};

int main()
{
int (*p)[] = &C::v; // works in C++ if 'v' isn't defined (only declared)
return 0;
}

但找不到此代码的任何有用案例。

谁能给出一个有用的例子(在 C++ 中)指向具有未指定边界的数组的指针?还是只剩下C的痕迹?

最佳答案

这样的指针不能参与指针运算,仍然可以做的潜在有用的事情是使用 decltypereinterpret_cast 将其类型转换为另一个指针类型或 intptr_t。这是因为第 3.9p6 节说:

A class type (such as "class X") might be incomplete at one point in a translation unit and complete later on; the type "class X" is the same type at both points. The declared type of an array object might be an array of incomplete class type and therefore incomplete; if the class type is completed later on in the translation unit, the array type becomes complete; the array type at those two points is the same type. The declared type of an array object might be an array of unknown size and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points ("array of unknown bound of T" and "array of N T") are different types. The type of a pointer to array of unknown size, or of a type defined by a typedef declaration to be an array of unknown size, cannot be completed.

5.3.1 说:

Note: indirection through a pointer to an incomplete type (other than cv void) is valid. The lvalue thus obtained can be used in limited ways (to initialize a reference, for example); this lvalue must not be converted to a prvalue, see 4.1.

由于可以对数组左值执行数组到指针的衰减,而无需事先转换为右值,因此注释中留下的代码 dyp 是正确的:

(*p)[i]

相关规则,从 4.2 开始:

An lvalue or rvalue of type 'array of N T" or "array of unknown bound of T" can be converted to a prvalue of type "pointer to T". The result is a pointer to the first element of the array.

关于c++ - 在 C++ 中(不在 C 中)具有未指定边界的数组指针的可用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24478830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com