我不明白以下指针变量声明在 c 中的含义
char(*p)[15];
char(*p)(int *a);
int(*pt)(char*);
>int *pt(char*);
有人帮忙吗?
char(*p)[15];
char(*p)(int *a);
int(*pt)(char*);
int *pt(char*);
anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本规则:从标识符开始,可以向右阅读,必须向左阅读。
)
。将你的“右脚”放在)
所在位置的右侧一个字符(如果这就是你击中的位置)。[42]
,请说“array of 42”。(
,请说“函数获取”,然后递归说出每个参数的类型(但省略参数名称本身),然后通过“并返回”。(
。如果是的话,将你的左脚放在(
左边一个字符你击中了。*
或&
,请说“指向”或“引用”。const
、int
、MyFoo
),只需说出来即可。* 如果没有标识符,想象它必须去哪里——我知道这很棘手,但只有一个合法的位置。
遵循以下规则:
Basic rule: Start at the identifier and read right when you can, left when you must.
)
. Put your "right foot" one character to the right of where that)
is, if that's what you hit.[42]
as you read rightwards, say "array of 42".(
as you read rightwards, say "function taking", then recurse to say each parameter's type (but omit the parameter names themselves), followed by "and returning".(
. Put your left foot one character to the left of the(
if that's what you hit.*
or a&
as you read leftwards, say "pointer to" or "reference to".const
,int
,MyFoo
), just say it.* If there is no identifier, imagine where it must go -- tricky I know, but there's only one legal placement.
Following these rules:
找出指针指向什么类型的一个简单技巧是删除
*
并查看剩下的内容:char p[15];
char p(int *a);
int pt(char*);
int pt(char*);
您得到的是指针将指向的类型的变量声明到。或者不是第四种情况:
是函数原型而不是有效的指针声明。
编辑:
原因是没有括号,函数调用“运算符”优先于指针取消引用运算符。在上面的例子中,简单英语的声明是:
我们有一个
pt(char *)
函数,它返回一个int *
而
翻译为:
*pt
是一个接受char *
并返回int
的函数。这本质上意味着 pt 本身就是指向该类型的指针。
A simple trick to find out what type a pointer points to is to just remove the
*
and see what's left:char p[15];
char p(int *a);
int pt(char*);
int pt(char*);
What you get is a variable declaration of the type your pointer will point to. Or not in the fourth case:
is a function prototype and not a valid pointer declaration.
EDIT:
The reason is that without the parentheses, the function call "operator" takes precedence over the pointer dereference operator. In the case above, the declaration in plain English is:
We have a
pt(char *)
function, which returns anint *
While
translates as:
*pt
is a function that takes achar *
and returns anint
.Which essentially means that
pt
on its own is a pointer to that type.