关于数组和指针混合的声明
about the declaration of a mixture of array and pointer
谁能解释一下声明数组和指针混合的规则?
下面是我的发现。但是,我不明白为什么int *p[10]
表示an allocation of 10 consecutive memory blocks (each can store data of type int *)
,而int (*p)[10]
表示declaring a pointer to an array of 10 consecutive memory blocks (each can store data of type int)
。这些代码背后的规则是什么?
int p[10]; //10 consecutive memory blocks (each can store data of type int) are allocated and named as p
int *p[10]; //10 consecutive memory blocks (each can store data of type int *) are allocated and named as p
int (*p)[10]; //p is a pointer to an array of 10 consecutive memory blocks (each can store data of type int)
目前,我猜规则是:
xxx[10]
将被解释为please allocating 10 memory blocks in which each blocks may store xxx
。因此,int *p[10]
会得到10 memory blocks in which each can store data of type int *
;
()
,(*p)
将首先被解释,这将导致指向某个地方的指针。因此,int (*p)[10]
将得到a pointer to an array of 10 consecutive memory blocks (each can store data of type int)
。
C使用中缀符号表示类型。一个包含10个int类型的数组的类型是int [10]
,但是任何从数组类型派生的,其派生都在int
和[10]
之间(不像在其他语言中那样在末尾)。
如果我们声明了一个具有这种类型的变量,它不是int [10] arr;
,而是int arr [10];
同样,指向10个int型数组的指针不是int [10] *
,而是int (*) [10]
。
需要()
的原因是int * [10]
将是一个包含10个int *
的数组。()
有分解int
和*
的作用,所以它不能被解析为int *
类型。除此之外,它们没有"任何意义"。
你实际上已经引用了规则。唯一需要补充的是,您最好这样写:
int* p[10];
^------ belongs to int
int (*p)[10];
^---- belongs to p, ie p is pointer to int[10]
如果您不确定,您可以随时查看http://cdecl.org/
PS:实际上,从语法上讲,写(1)比写(2)更有意义:
int *a; // (1)
int* a; // (2)
因为声明两个指针必须这样写:
int *a,*b; // and not int *a,b; !!
然而,从语义上讲,*
是类型的一部分,即。(1)和(2)都声明了一个名为a
的(int*)
,用(2)来表达更清楚。因此,多个指针的声明通常放在单独的行上:
int* a;
int* b;
- 参数的混合值,当我调用指针成员函数时
- 将指向类对象的智能指针与类对象混合使用
- 混合转换指针和引用
- 混合索引和指针算术时避免使用C4365,而无需铸造
- 混合指向已分配对象和作用域对象的指针
- 原始指针和智能指针混合函数重载
- C++和混合编程中指针的默认参数
- C++将unqiue_ptr与同一对象的原始指针混合在一起
- 混合 C/C++ 代码中的结构指针
- MinGW 4.7.0 到 4.7.2 错误:使用混合虚拟和非虚拟多重继承时成员函数中的"this"指针无效
- 如何混合C++共享指针和对象引用
- 混合代码-函数成员指针
- 期望输出带有指针和引用混合的代码
- 关于数组和指针混合的声明
- c++混合指向不同char类型的指针
- c++中函数定义中指针和引用的混合
- 在c++类中混合指向构造结构的指针——在参数列表中声明结构
- 如何混合boost::bind与C函数指针来实现回调
- 混合程序(asm+cpp):发送和接收一个数组指针
- 为什么指向不同char类型的指针不能混合,而不同char类型的变量可以相互转换