在进行指针定义时,如:intp,是将“int”看成整体还是将“*p”看成整体?
都不是,它就是单独的一个
你写作以下两种,语法都对
int* p
int *p
将*p
看成一个整体,下面是几个复杂一点的例子。
From https://en.cppreference.com/w/cpp/language/declarations
#include <string>
class C {
std::string member; // decl-specifier-seq is "std::string"
// declarator is "member"
} obj, *pObj(&obj);
// decl-specifier-seq is "class C { std::string member; }"
// declarator "obj" defines an object of type C
// declarator "*pObj(&obj)" declares and initializes a pointer to C
int a = 1, *p = nullptr, f(), (*pf)(double);
// decl-specifier-seq is int
// declarator a = 1 defines and initializes a variable of type int
// declarator *p = nullptr defines and initializes a variable of type int*
// declarator (f)() declares (but doesn't define)
// a function taking no arguments and returning int
// declarator (*pf)(double) defines a pointer to function
// taking double and returning int
int (*(*foo)(double))[3] = nullptr;
// decl-specifier-seq is int
// 1. declarator "(*(*foo)(double))[3]" is an array declarator:
// the type declared is "/nested declarator/ array of 3 int"
// 2. the nested declarator is "(*(*foo)(double))", which is a pointer declarator
// the type declared is "/nested declarator/ pointer to array of 3 int"
// 3. the nested declarator is "(*foo)(double)", which is a function declarator
// the type declared is "/nested declarator/ function taking double and returning
// pointer to array of 3 int"
// 4. the nested declarator is "(*foo)" which is a (parenthesized, as required by
// function declarator syntax) pointer declarator.
// the type declared is "/nested declarator/ pointer to function taking double
// and returning pointer to array of 3 int"
// 5. the nested declarator is "foo", which is an identifier.
// The declaration declares the object foo of type "pointer to function taking double
// and returning pointer to array of 3 int"
// The initializer "= nullptr" provides the initial value of this pointer.
p是指针变量的名字int*p
代表这个指针变量的类型是int*类型,是一个整型指针(int是整型,*代表是指针变量)
实际语法的时候不管你*靠近int还是靠近p都是正确的。
个人认为应该把int*看作整体,因为它才是变量p的类型
意思是一样的,个人倾向把int *作为整体。
int ,p表示定义一个变量p,它的类型是int * 。
int, * p 表示定义某个整形变量,该整形变量可以用 p读取和赋值
一般来说是是 int* 作为整体,就与前几楼说的, (int*) 才是p的类型, 内存分配也是按照 (int*) 的大小分配。
但有一种特别的情况, int *p 与 int (*p) 是不同的,后者常用于函数指针,怎么区分整体也不是很清楚。 个人认为int (*p) 应是 *p 为整体, 因为前面的 int 是这个指针函数的返回类型。
两种都是可以的,哪一种便于自己理解和其他人阅读就采用哪一种,推荐看看这篇文章:
[C/C++中指针类型声明: *的位置] https://zhuanlan.zhihu.com/p/107917657