很难理解char(*p)的优先原则[sizeof(c)];

Pip*_*eek 6 c c++ pointers

我正在学习指针并挑战自己,我尝试取消引用指向字符数组的指针.最终这有效:

char (*p)[sizeof(c)];
Run Code Online (Sandbox Code Playgroud)

其中c是数组c [] ="something"

我很难理解与众不同(*p)[sizeof(c)];之处*p[sizeof(c)];

基于我目前所知的(这并不多!)计算机在以下情况下这样说(*p)[sizeof(c)];:

"p指向c!哦,顺便说一句,p是任何大小的数组(c)最终都是".

但即使这对我来说也很奇怪,所以我想我在添加括号时会对构造的内容感到困惑.

谁能解释一下?

完整代码在上下文中:

#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {

    char c[] = "something";

    char (*p)[sizeof(c)]; // this works
    // char *p[sizeof(c)]; // this doesn't?

    p = &c;

    cout << p << endl;  

    cout << *p << endl;
}
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 14

可以使用非正式称为左右规则的内容来读取C中的类型.您从声明的变量的名称开始,然后在您可以的情况下向右移动,然后在您可以的情况下向左移动,然后重新开始.圆括号会阻止您,直到考虑了所有内容为止.

在你的例子中:

char (*p)[sizeof(c)];
       ^               p...                          (hit ')', turn around)
      ^                is a pointer...               (hit '(', turn around and remove '()')
         ^^^^^^^^^^^   to an array of `sizeof(c)`... (end of line, turn around)
^^^^                   chars.                        nothing left, we're done!
Run Code Online (Sandbox Code Playgroud)

没有括号,这变为:

char *p[sizeof(c)];
      ^^^^^^^^^^^^     p is an array of `sizeof(c)`... (end of line, turn around)
^^^^^^                 pointers to char.
Run Code Online (Sandbox Code Playgroud)

这确实是完全不同的.

  • @Pipsqweek也请不要在语法挑战之外写出这样的恐怖.我花了五分钟的时间来检查我上面的括号毛虫是否犯了错误...... (2认同)