【问题标题】:pointer to function to structure, pointer to function to typedef指向结构的函数指针,指向 typedef 的函数指针
【发布时间】:2013-12-29 00:42:57
【问题描述】:

下面 pointer_to_structure.c 中的代码可以正常工作,但 pointer_to_type-def.c 中的代码不行,我不明白错误。

我会感谢任何更正代码的人。

pointer_to_structure.c

#include <stdio.h>

struct sum {
  int a,b,c;
} sum_operation,*ptr;


int main(){

  ptr = &sum_operation;

  (*ptr).a = 1;
  (*ptr).b = 3;

  (*ptr).c =(*ptr).b + (*ptr).a  ;

  printf("%d\n",(*ptr).c);

  return 0;
}

pointer_to_type-def.c

#include <stdio.h>

typedef struct sum {
  int a,b,c;
}sum_operation,*ptr;


int main(){

  ptr = &sum_operation;   //this should be changed

  (*ptr).a = 1;
  (*ptr).b = 3;

  (*ptr).c =(*ptr).b + (*ptr).a  ;

  printf("%d\n",(*ptr).c);

  return 0;
}

【问题讨论】:

    标签: function pointers typedef


    【解决方案1】:

    这应该可以工作

    #include <stdio.h>
    
    typedef struct sum {
    int a,b,c;
    } mytype;
    
    
    int main(){
    
    mytype  sum_operation;
    mytype *ptr;
    
    ptr = &sum_operation;   //this should be changed
    
    (*ptr).a = 1;
    (*ptr).b = 3;
    
    (*ptr).c =(*ptr).b + (*ptr).a  ;
    
    printf("%d\n",(*ptr).c);
    
    return 0;
    }
    

    提示:当您使用 typedef 时,它会为该结构创建一个类型别名。因此 sum_operation 是代码中的一种结构。在固定代码中,使用 typedef 为结构赋予别名“mystruct”,并使用该别名类型创建对象,然后正常对其进行操作。

    另外,您的评论不正确。如果只更改单个语句,代码将无法正常工作。

    【讨论】:

    • 点击左侧的勾选箭头,如果有效,则接受答案。
    • 你有邮箱吗?怎么联系你?
    【解决方案2】:

    当你使用时

    typedef struct sum {
    int a,b,c;
    }sum_operation,*ptr;
    

    相当于声明

    struct sum {
        int a,b,c;
    };
    
    typedef struct sum sum_operation;
    

    因此,sum_operation 现在变成了typedef。所以你不能使用指针来获取sum_operation 的地址,因为它只是一个类型。你需要使用

    sum_operation another;
    sum_operation *ptr;
    

    然后你就可以了

    ptr = &another;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2011-03-04
      • 2010-12-05
      • 2011-04-26
      相关资源
      最近更新 更多