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


#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. 解释此&p->i。为什么这代表成员变量i?

  2. 的地址
  3. scanf("%d",&(*p).i);有效吗?为什么?

在您的情况下

  • &p->i&(p->i)相同,因为操作员优先。
  • &(*p).i&(p->i)相同。

,它们都按照scanf()函数参数基于提供的转换说明符的要求。

但是,

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

无效,因为p->i为您提供了int,而您需要一个指针到整数。

scanf期望某物指针,以便根据您提供给函数的格式 store 数据。

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

p->i从指向p指向的结构中为您提供整数i
&p->i给出了i地址,Scanf。

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

是的,这与上面相同。(*p).ip->i

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

scanf需要一个指针来存储"%d",这意味着整数;但是,在这里您给出了i的值,而不是i的指针。

最新更新