【问题标题】:Using Pointer to Struct to read member Variables使用指向结构的指针来读取成员变量
【发布时间】:2017-11-22 14:04:03
【问题描述】:
#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. 解释这个&amp;p-&gt;i。为什么这个代表成员变量i的地址?

  2. 这是scanf("%d",&amp;(*p).i); 有效吗?为什么?

【问题讨论】:

  • 请不要即时为问题输入代码。先离线做,编译然后复制粘贴。您的代码不可能是您实际尝试过的。它到处都是不正确的。
  • 这是我编辑的错字
  • 请注意,main() 中的局部变量 i 未使用,与同名结构成员完全无关。
  • 另请注意,当您需要多个级别时,箭头运算符比“星点”表示法更可取。例如,p-&gt;next-&gt;next 比使用星号、圆点和括号的等价物更容易输入和阅读。

标签: c pointers structure scanf


【解决方案1】:

你的情况

  • &amp;p-&gt;i&amp;(p-&gt;i) 相同,因为 operator precedence
  • &amp;(*p).i&amp;(p-&gt;i) 相同。

并且它们都根据提供的转换说明符根据scanf() 函数参数的要求生成一个指向整数的指针。

然而,

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

无效,因为p-&gt;i 为您提供int,而您需要一个指向整数的指针。

【讨论】:

  • 你能解释一下为什么我可以取消引用 (p->i)
  • @rimiro 不确定我是否理解您的问题。 :(
  • 我的问题是为什么&amp;(p-&gt;i)代表成员var i的地址。让我感到困惑的是,既然 p 是一个指针,那么为什么 p-&gt;i 不是指向成员变量 i 的指针。
  • @rimiro nope,-&gt; 只给你成员,而不是指向成员的指针。
  • 这就是我想知道的
【解决方案2】:

scanf 需要一个指向某物的指针,以便根据您提供给函数的格式存储数据。

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

p-&gt;i 为您提供p 指向的结构中的整数i
&amp;p-&gt;i 提供i地址,这是scanf 所需的。

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

是的,和上面一样。 (*p).ip-&gt;i

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

scanf 需要一个指针来存储一个“%d”,意思是一个整数;不过,这里给出的是i 的值,而不是指向i 的指针。

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多