结构体函数指针成员与函数指针类型的结构体类型形参的相互嵌套定义及使用问题...

@2018-10-24

结构体函数指针成员与函数指针类型的结构体类型形参的相互嵌套定义及使用问题

具体代码

 1 #include <stdio.h>
 2 
 3 #define METHOD            0
 4 
 5 
 6 #if METHOD
 7 
 8 typedef void(*pf)(struct _struct *parameter);
 9 
10 #else
11 /* VC++6.0此法报错,gcc编译OK */
12 struct _struct;
13 typedef void(*pf)(struct _struct parameter);
14 
15 #endif
16 
17 
18 struct _struct
19 {
20     int i;
21     pf fun;
22 };
23 
24 #if METHOD
25 
26 void testFun(struct _struct *parameter)
27 {
28     printf("这是一个函数指针与结构体定义的先后问题!\n");
29     printf("testObj.i = %d\n", parameter->i);
30 }
31 
32 #else
33 
34 void testFun(struct _struct parameter)
35 {
36     printf("这是一个函数指针与结构体定义的先后问题!\n");
37     printf("testObj.i = %d\n", parameter.i);
38 }
39 
40 #endif
41 
42 
43 int main()
44 {
45     struct _struct testObj;
46 
47     testObj.i = 99;
48     testObj.fun = testFun;
49 
50 #if METHOD
51     testObj.fun(&testObj);
52 #else
53     testObj.fun(testObj);
54 #endif
55 }

 

转载于:https://www.cnblogs.com/skullboyer/p/9842287.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当我们需要在函数中操作结构体类型的数据时,可以将结构体类型作为函数的形参,这样在函数内部就可以对结构体类型数据进行操作。 如果结构体嵌套了其他结构体,我们可以将嵌套结构体类型作为结构体类型成员之一,并在函数参数中传递该结构体类型。 例如,定义一个名为 `Student` 的结构体类型,其中嵌套了一个名为 `Birthday` 的结构体类型,代码如下: ```c #include <stdio.h> struct Birthday { int year; int month; int day; }; struct Student { char name[20]; int age; struct Birthday birthday; }; void printStudent(struct Student stu) { printf("Name: %s\n", stu.name); printf("Age: %d\n", stu.age); printf("Birthday: %d-%02d-%02d\n", stu.birthday.year, stu.birthday.month, stu.birthday.day); } int main() { struct Student stu = {"Tom", 18, {2000, 1, 1}}; printStudent(stu); return 0; } ``` 在上面的示例中,我们定义了一个名为 `Birthday` 的结构体类型和一个名为 `Student` 的结构体类型,`Student` 结构体嵌套了 `Birthday` 结构体类型。在 `printStudent` 函数中,我们将 `Student` 结构体类型作为参数传递,可以直接通过 `stu.birthday` 访问嵌套的 `Birthday` 结构体类型成员变量。 当然,我们也可以将 `Student` 结构体类型的指针作为函数参数,代码如下: ```c void printStudent(struct Student *pStu) { printf("Name: %s\n", pStu->name); printf("Age: %d\n", pStu->age); printf("Birthday: %d-%02d-%02d\n", pStu->birthday.year, pStu->birthday.month, pStu->birthday.day); } int main() { struct Student stu = {"Tom", 18, {2000, 1, 1}}; printStudent(&stu); return 0; } ``` 注意,在函数中访问结构体类型成员变量时,可以使用 `.` 运算符或 `->` 运算符,前者用于结构体类型变量,后者用于结构体类型指针。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值