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

让我们考虑下面的例子。

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

类似地,我们可以有

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

等等。

例如,

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

当前回答

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

其他回答

我想指出的是,生成带有任意数量*的类型是可以通过模板元编程实现的。我忘了我到底在做什么,但有人建议我可以通过使用递归T*类型来生成新的不同类型,这些类型之间具有某种元操作。

模板元编程是一个慢慢陷入疯狂的过程,所以在生成一个有几千个间接层的类型时,没有必要找借口。例如,它只是将peano整数作为函数式语言映射到模板展开的一种方便方法。

实际上,C程序通常使用无限指针间接。一个或两个静态级别是常见的。三重间接是很少见的。但是无限是很常见的。

无限指针间接是在结构的帮助下实现的,当然,不是通过直接的声明器,这是不可能的。需要一个结构体,这样你就可以在不同的层次上在这个结构中包含其他数据。

struct list { struct list *next; ... };

现在你可以有list->next->next->next->…->next。这实际上只是多个指针指向:*(*(..(*(*(*list).next).next).next…).next).next).next。当。next是这个结构的第一个元素时,它基本上就是一个noop,所以我们可以把它想象成***. ***ptr。

这实际上没有任何限制,因为链接可以通过循环来遍历,而不是像这样一个巨大的表达式,而且,结构可以很容易地变成圆形。

因此,换句话说,链表可能是添加另一层间接来解决问题的最终示例,因为您对每个推操作都是动态地进行操作的。:)

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

#include <cstdio>

typedef void (*FuncType)();

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

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

如下图所示:

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

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

听起来很有趣。

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

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

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