【问题标题】:The more complex notation of the Structure Dereference operator in C, ->?C 中结构取消引用运算符的更复杂的表示法,->?
【发布时间】:2014-05-20 01:42:05
【问题描述】:

我这里有一个考试题,问:

“C 运算符 -> 是更复杂符号的简写。解释在什么情况下使用 -> 或更复杂的符号。写一个更复杂符号的示例。”

我不确定考官在这里寻找什么。我的印象是只有一种方式来表示结构取消引用,那就是 ->。有人可以帮忙吗?

【问题讨论】:

  • 你将如何取消引用一个对象(不是访问一个成员;只是取消引用它)?如果你有一个对象(不是指针),你如何访问一个成员?
  • 在问这里之前先做一些研究,你清楚地知道它是取消引用的简写......那么我们怎么能找出其他符号......Google is your friend

标签: c operators structure dereference


【解决方案1】:

-> 语法是(*). 语法的简写,所以struct->member 等价于(*struct).member

括号是强制性的,因为operator priority,基本上这里成员访问(.)运算符比取消引用(*)运算符具有更高的优先级。

请记住,程序员很懒惰,通常喜欢捷径。

【讨论】:

    【解决方案2】:

    可以使用->(*). 来完成取消引用。看例子

    struct point {
      int x;
      int y;
    };
    struct point my_point = { 3, 7 };
    struct point *p = &my_point;  /* To declare and define p as a pointer of type struct point,
                                     and initialize it with the address of my_point. */
    
    (*p).x = 8;                   /* To access the first member of the struct */
    p->x = 8;    
    

    很可能你的老师要求(*p).x = 8;

    【讨论】:

      猜你喜欢
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2014-11-08
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      相关资源
      最近更新 更多