在一个变量中允许有多少个指针(*)?
让我们考虑下面的例子。
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;
当前回答
2004 MISRA C标准的17.5规则禁止超过2级的指针间接。
其他回答
请注意,这里可能存在两个问题:在C类型中可以实现多少层指针间接,以及在单个声明器中可以填充多少层指针间接。
C标准允许对前者施加一个最大值(并给出一个最小值)。但这可以通过多个typedef声明来避免:
typedef int *type0;
typedef type0 *type1;
typedef type1 *type2; /* etc */
因此,最终,这是一个实现问题,与C程序在被拒绝之前可以做出多大/多复杂的想法有关,这是非常特定于编译器的。
正如人们所说,“理论上”没有限制。然而,出于兴趣,我用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;
}
这取决于你存储指针的位置。如果它们是堆叠的,极限就会很低。如果你把它存储在堆里,你的极限会非常非常高。
看看这个程序:
#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,所以想象一下你能走多深。
每个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.
2004 MISRA C标准的17.5规则禁止超过2级的指针间接。