在一个变量中允许有多少个指针(*)?
让我们考虑下面的例子。
int a = 10;
int *p = &a;
类似地,我们可以有
int **q = &p;
int ***r = &q;
等等。
例如,
int ****************zz;
在一个变量中允许有多少个指针(*)?
让我们考虑下面的例子。
int a = 10;
int *p = &a;
类似地,我们可以有
int **q = &p;
int ***r = &q;
等等。
例如,
int ****************zz;
当前回答
这取决于你存储指针的位置。如果它们是堆叠的,极限就会很低。如果你把它存储在堆里,你的极限会非常非常高。
看看这个程序:
#include <iostream>
const int CBlockSize = 1048576;
int main()
{
int number = 0;
int** ptr = new int*[CBlockSize];
ptr[0] = &number;
for (int i = 1; i < CBlockSize; ++i)
ptr[i] = reinterpret_cast<int *> (&ptr[i - 1]);
for (int i = CBlockSize-1; i >= 0; --i)
std::cout << i << " " << (int)ptr[i] << "->" << *ptr[i] << std::endl;
return 0;
}
它创建了1M个指针,并在显示什么指向什么时很容易注意到链到第一个变量数。
顺便说一句。它使用92K的RAM,所以想象一下你能走多深。
其他回答
正如人们所说,“理论上”没有限制。然而,出于兴趣,我用g++ 4.1.2运行了这个程序,它可以在大小为20,000的情况下工作。编译非常慢,所以我没有尝试更高的编译。所以我猜g++也没有施加任何限制。(尝试设置size = 10,如果不是很明显,可以在ptr.cpp中查看。)
g++ create.cpp -o create ; ./create > ptr.cpp ;G++ PTR.cpp -optr ; ./PTR
create.cpp
#include <iostream>
int main()
{
const int size = 200;
std::cout << "#include <iostream>\n\n";
std::cout << "int main()\n{\n";
std::cout << " int i0 = " << size << ";";
for (int i = 1; i < size; ++i)
{
std::cout << " int ";
for (int j = 0; j < i; ++j) std::cout << "*";
std::cout << " i" << i << " = &i" << i-1 << ";\n";
}
std::cout << " std::cout << ";
for (int i = 1; i < size; ++i) std::cout << "*";
std::cout << "i" << size-1 << " << \"\\n\";\n";
std::cout << " return 0;\n}\n";
return 0;
}
听起来很有趣。
Visual Studio 2010(在Windows 7上),在得到这个错误之前,你可以有1011个级别: 解析器堆栈溢出,程序太复杂 gcc (Ubuntu), 100k+ *没有崩溃!我想硬件是这里的极限。
(仅用变量声明进行测试)
2004 MISRA C标准的17.5规则禁止超过2级的指针间接。
C标准规定了下限:
5.2.4.1翻译限制 实现应能够翻译和执行至少一个包含以下每个限制的至少一个实例的程序:[…] 279 - 12指针、数组和函数声明符(任意组合) 声明中的算术、结构、联合或空类型
上限是特定于实现的。
每个c++开发人员都应该听说过著名的三星程序员。
而且似乎真的有某种神奇的“指针障碍”必须被掩盖。
C2引用:
Three Star Programmer A rating system for C-programmers. The more indirect your pointers are (i.e. the more "*" before your variables), the higher your reputation will be. No-star C-programmers are virtually non-existent, as virtually all non-trivial programs require use of pointers. Most are one-star programmers. In the old times (well, I'm young, so these look like old times to me at least), one would occasionally find a piece of code done by a three-star programmer and shiver with awe. Some people even claimed they'd seen three-star code with function pointers involved, on more than one level of indirection. Sounded as real as UFOs to me.