[英]Pointer confusion in C programming language
Hello guys and a happy new year! 大家好,新年快乐!
I have difficulty understanding pointers in C language. 我很难理解C语言中的指针。 As far as I learned a pointer is a special variable that stores addresses of regular variables. 据我所知,指针是一个存储常规变量地址的特殊变量。
Ι am posting two samples of code which are equivalent. 我正在发布两个相同的代码示例。 In the first I typed into scanf the &d1.am
. 在第一次我输入scanf &d1.am
。
In the second sample if I change the &d1.am
to ptd1.am
it pops up a compile error and I cannot understand why. 在第二个示例中,如果我将&d1.am
更改为&d1.am
, ptd1.am
弹出编译错误 ,我无法理解原因。
struct student{
int am;
char stname[20];
char stsurname[20];
};
int main(){
struct student d1;
printf("1st student\n");
printf("Enter am\n");
scanf("%d", &d1.am)
Second equivalent sample: 第二个等效样本:
struct student{
int am;
char stname[20];
char stsurname[20];
};
int main(){
struct student d1;
struct student *ptd1;
ptd1=&d1;
printf("1st student\n");
printf("Enter am\n");
scanf("%d", &(*ptd1).am);
I know the correct is to type &(*ptd1).am
instead but I can't figure why. 我知道正确的是键入&(*ptd1).am
而不是我无法&(*ptd1).am
为什么。 How &(*ptd1).am
is equal to &d1.am
and ptd1.am
is not? 怎么&(*ptd1).am
等于&d1.am
而ptd1.am
? I typed clearly that ptd1=&d1
! 我清楚地输入了ptd1=&d1
!
Thanks in advance for your help! 在此先感谢您的帮助!
.
operator has higher precedence than unary &
. 运算符的优先级高于一元&
。 &d1.am
is equivalent to &(d1.am)
while ptd1.am
is equivalent to (&d1).am
, that said &d1.am
!= (&d1).am
. &d1.am
相当于&(d1.am)
而ptd1.am
相当于(&d1).am
,表示&d1.am
!= (&d1).am
。
The structure access operator ( .
) has higher precedence than the address-of operator ( &
). 结构访问运算符( .
)的优先级高于运算符地址( &
)。 So &d1.am
is the address of the am
member of d1
, which is an int*
, which differs from the type of ptd1
( struct student *
). 所以&d1.am
是d1
的am
成员的地址,它是一个int*
,它与ptd1
( struct student *
)的类型不同。
Has other have said the .
还有其他人说过.
operator has higher precedence than &
. 运算符的优先级高于&
。 So that ptd1.am is equivalent to (&d1).am (see for example the answer from @haccks). 所以ptd1.am相当于(&d1).am(例如参见@haccks的回答)。
I want to add that ptd1 is a pointer to struct and thus to get a member you should use ->
. 我想补充一点, ptd1是一个指向struct的指针 ,因此要获得一个你应该使用的成员->
。 The call to scanf should be: 对scanf的调用应该是:
scanf("%d", &(ptd1->am));
As u have written ptd1=&d1; 你写的是ptd1 =&d1; that means that *ptd1 will point to d1 . 这意味着* ptd1将指向d1。
So if you want to access d1.am you need to write (*ptd1).am . 所以如果你想访问d1.am,你需要写(* ptd1).am。
But here you are passing to scanf and it needs memory address so need to pass with & and so you need to put &(*ptd1).am. 但是在这里你传递给scanf它需要内存地址所以需要传递&所以你需要把&(* ptd1).am。
As others have mentioned (.) has higher priority so (.) will choose it operands first and expression will be equal to 正如其他人提到的那样(。)具有更高的优先级,因此(。)将首先选择操作数并且表达式将等于
&((*ptd1).am) &((* PTD1).AM)
Better to use &(ptd1->am) 最好使用&(ptd1-> am)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.