简体   繁体   English

使用指针构造读取成员变量

[英]Using Pointer to Struct to read member Variables

#include<stdio.h>

struct data{
    int i;
    struct data *p;
};

int main() {
    struct data *p=malloc(sizeof(struct data));

    //How do i use pointer to structure to read a integer in member variable i?

    scanf("%d",&p->i);    // I am advised to use this,Can you interpret this??
    scanf("%d",&(*p).i);  // Is this valid?
    scanf("%d",p->i);     // Why is this not valid since p is nothing but a pointer 
}
  1. Interpret this &p->i . 解释&p->i Why this represents the address of the member variable i? 为什么这代表成员变量i的地址?

  2. Is this scanf("%d",&(*p).i); 这是scanf("%d",&(*p).i); valid? 有效? Why? 为什么?

In your case 就你而言

  • &p->i is the same as &(p->i) because of the operator precedence . &p->i是相同的&(p->i)因为的操作优先级
  • &(*p).i is the same as &(p->i) . &(*p).i&(p->i)

and they both produce a pointer to an integer, as required by the scanf() function argument based on the supplied conversion specifier. 它们都根据提供的转换说明符,根据scanf()函数参数的要求,产生一个指向整数的指针。

However, 然而,

 scanf("%d",p->i);

is not valid, as p->i gives you an int , whereas, you need a pointer to integer. 是无效的,因为p->i给您一个int ,而您需要一个指向整数的指针。

scanf expects a pointer to something, in order to store data according to the format you provide to the function. scanf需要一个指向某物的指针,以便根据您提供给该函数的格式存储数据。

scanf("%d",&p->i); // I am advised to use this,Can you interpret this??

p->i gives you the integer i from the structure pointed to by p . p->ip指向的结构中得到整数i
&p->i gives the address of i , required by scanf. &p->i给出scanf所需的i地址

scanf("%d",&(*p).i);  //Is this valid?

Yes, that's the same as above. 是的,和上面一样。 (*p).i is p->i (*p).ip->i

scanf("%d",p->i);  //Why is this not valid since p is nothing but a pointer 

scanf needs a pointer to store a "%d", meaning an integer ; scanf需要一个指针来存储“%d”,即整数; though, here you give the value of i , not a pointer to i . 不过,在这里你给的值i ,而不是指向i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM