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

让我们考虑下面的例子。

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

类似地,我们可以有

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

等等。

例如,

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

当前回答

请注意,这里可能存在两个问题:在C类型中可以实现多少层指针间接,以及在单个声明器中可以填充多少层指针间接。

C标准允许对前者施加一个最大值(并给出一个最小值)。但这可以通过多个typedef声明来避免:

typedef int *type0;
typedef type0 *type1;
typedef type1 *type2; /* etc */

因此,最终,这是一个实现问题,与C程序在被拒绝之前可以做出多大/多复杂的想法有关,这是非常特定于编译器的。

其他回答

从理论上讲:

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

实际:

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

参考资料如下:

5.2.4.1翻译限制:

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

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

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

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

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

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

int **q = &p;

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

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

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

是被允许的。

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

听起来很有趣。

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

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

实际上,使用指向函数的指针更有趣。

#include <cstdio>

typedef void (*FuncType)();

static void Print() { std::printf("%s", "Hello, World!\n"); }

int main() {
  FuncType const ft = &Print;
  ft();
  (*ft)();
  (**ft)();
  /* ... */
}

如下图所示:

你好,世界! 你好,世界! 你好,世界!

而且它不涉及任何运行时开销,所以你可以尽可能多地堆叠它们……直到编译器被文件阻塞。