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

让我们考虑下面的例子。

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;
}

听起来很有趣。

Visual Studio 2010(在Windows 7上),在得到这个错误之前,你可以有1011个级别: 解析器堆栈溢出,程序太复杂 gcc (Ubuntu), 100k+ *没有崩溃!我想硬件是这里的极限。

(仅用变量声明进行测试)

没有限制。指针是一个内存块,其内容是一个地址。 如你所说

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

指向指针的指针也是一个变量,它包含另一个指针的地址。

int **q = &p;

这里q是指针到指针的指针,持有p的地址,p已经持有a的地址。

指针指向指针没有什么特别之处。因此,存储另一个指针地址的指针链是没有限制的。 ie。

 int **************************************************************************z;

是被允许的。

2004 MISRA C标准的17.5规则禁止超过2级的指针间接。