C中的指针声明约定

Atu*_*tul 2 c pointers

这可能是之前讨论过的.但到目前为止我找不到任何参考.所以想发布它.

当我们声明指针(比如int类型)时,我们写,

int* pointer;
Run Code Online (Sandbox Code Playgroud)

int*数据类型在哪里(因此我们可以做typedef int* PTR_TO_INT;,然后可以声明类型的变量PTR_TO_INT)

但是当我们想要声明多个指针时,为什么我们需要为每个指针添加*?

int* pointer1, pointer2, pointer3; // Only first is pointer. Rest are integers
Run Code Online (Sandbox Code Playgroud)

虽然在这种情况下它是不同的惯例:

PTR_TO_INT pointer1, pointer2, pointer3; // All are pointers.
Run Code Online (Sandbox Code Playgroud)

例:

int _tmain(int argc, _TCHAR* argv[])
{
    typedef int* PTR_MYINT;
    PTR_TO_INT xyz, abc;
    int* xyz1, abc1;

    xyz = NULL;
    abc = xyz; // Valid, as both are pointers

    abc1 = xyz1; // Invalid, as abc1 is not pointer
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

too*_*ite 9

这不是"惯例",而是语法所要求的.的*:于权限令牌(在这里结合pointer1,而左侧(在这里int).这是什么原因,"公约"是写int *ip实际(因为你写它的时候取消引用指针lateron得到它指向的对象来).

所以

int *ip, i;
Run Code Online (Sandbox Code Playgroud)

有两个变量:指向int(ip)和int(i)的指针.

如果你需要两个指针:

int *ip1, *ip2;
Run Code Online (Sandbox Code Playgroud)

但是,为了文档目的,通常建议使用两行注释:

int *ip1;   // the first pointer
int *ip2;   // points to the next element
Run Code Online (Sandbox Code Playgroud)

这里的基类型是int.如果你有typedef

typedef int *IntPtr;
Run Code Online (Sandbox Code Playgroud)

定义的类型是指针int,因此如果您将其用作声明的基类型:

IntPtr ip1, ip2;
Run Code Online (Sandbox Code Playgroud)

你得到两个指针,因为上面的例子有基类型.

警告:这样typedef的可视化(即程序员,而不是编译器)隐藏了底层指针语义.这不仅危险,而且会让读者误导,因为你总是要注意这一点.你不应该这样做一般.几乎没有例外,但它们仅用于特殊用例.


注意:另一种看法

int *ip;
Run Code Online (Sandbox Code Playgroud)

is:*ip是类型int(对象类型视图).


Bat*_*eba 5

以类似于解除引用运算符*从右到左的关联性的方式,*用于指定类型的时间严格地绑定到右侧,而不是左侧令牌.

所以它与变量名称相关联,而不是类型说明符.

因此,您需要int * pointer1, * pointer2, * pointer3;根据个人喜好写出间距.

有效地typedef规避了这种相关性.