3

C语言指针最多有多少级?

 3 years ago
source link: https://www.zhihu.com/question/448862096/answer/1785538661
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
C语言指针最多有多少级? - 知乎
登录一下,更多精彩内容等你发现
贡献精彩回答,参与评论互动

没有限制。另外题主写100级指针不需要写100个星号,还容易出错。

template<typename T>
using AddPointer = T*;

template<typename T, size_t Depth>
struct DepthPointer:
    DepthPointer<AddPointer<T>, Depth - 1> { };

template<typename T>
struct DepthPointer<T, 0> {
    using type = T;
};

DepthPointer<int, 100>::type p100{};

怎么知道p100的类型?dump出来看看。

$ clang -Xclang -ast-dump -fsyntax-only test.cpp
`-FunctionDecl 0x226d460 <line:29:1, line:31:1> line:29:5 main 'int ()'
  `-CompoundStmt 0x22b0670 <col:12, line:31:1>
    `-DeclStmt 0x22b0658 <line:30:5, col:40>
      `-VarDecl 0x22b0570 <col:5, col:39> col:34 p100 'DepthPointer<int, 100>::type':'int ****************************************************************************************************' listinit
        `-InitListExpr 0x22b0618 <col:38, col:39> 'DepthPointer<int, 100>::type':'int ****************************************************************************************************'

确实是100级指针:'DepthPointer<int, 100>::type':'int ****************************************************************************************************'

另外这个超过1024级指针clang编译器会因为爆栈而挂掉,而gcc没有这个限制,想要多少级要多少级。测试的时候记得编译选项加上-ftemplate-depth=999999


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK