在一个变量中允许有多少个指针(*)?

让我们考虑下面的例子。

int a = 10;
int *p = &a;

类似地,我们可以有

int **q = &p;
int ***r = &q;

等等。

例如,

int ****************zz;

当前回答

每个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.

其他回答

请注意,这里可能存在两个问题:在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;
}

C标准规定了下限:

5.2.4.1翻译限制 实现应能够翻译和执行至少一个包含以下每个限制的至少一个实例的程序:[…] 279 - 12指针、数组和函数声明符(任意组合) 声明中的算术、结构、联合或空类型

上限是特定于实现的。

从理论上讲:

你可以有任意多的间接层次。

实际:

当然,任何消耗内存的操作都不能是无限的,主机环境中的可用资源会有限制。因此,实际上实现所能支持的内容是有最大限制的,实现应该适当地记录它。因此,在所有这些工件中,标准没有指定最大限度,但它指定了下限。

参考资料如下:

5.2.4.1翻译限制:

- 12个指针、数组和函数声明符(任意组合) 声明中的算术、结构、联合或空类型。

这指定了每个实现必须支持的下限。注意,在一个脚注中,标准进一步说:

18)实现应该尽可能避免强加固定的翻译限制。

每个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.