如何创建和调用函数指针
嗨,我是一名初学者,我正在尝试找出一些指向函数示例的指针。我什至无法编译我的代码,它显示以下消息。我无法确定为什么会出现编译错误。
/tmp/cc0qghbo.o: In function `main':
pointer_to_function_inside_structure.c:(.text+0x88): undefined reference to `func_ptr'
collect2: ld returned 1 exit status
这是我的代码,请告诉我我做错了什么
#include<stdio.h>
#include<stdlib.h>
struct student_data
{
char *name;
int roll_num;
int marks;
void (* func_ptr)(struct student_data *ptr);
};
void print_data(struct student_data *ptr);
void print_data(struct student_data *ptr)
{
printf("\nNAME OF THE STUDENT %s", ptr -> name);
printf("\nROLL NUMBER OF STUDENT %d", ptr -> roll_num);
printf("\nMARKS OF STUDENT %d\n", ptr -> marks);
}
int main()
{
struct student_data *ptr;
ptr -> name = "ajish";
ptr -> roll_num = 2;
ptr -> marks = 50;
ptr -> func_ptr = &print_data;
func_ptr(ptr);
}
Hi I'm a beginner and I'm trying to work out some pointer to function examples. I can't even compile my code, it shows the following message. I cannot determine why I am getting the compilation errors.
/tmp/cc0qghbo.o: In function `main':
pointer_to_function_inside_structure.c:(.text+0x88): undefined reference to `func_ptr'
collect2: ld returned 1 exit status
here is my code, please tell me what I'm doing wrong
#include<stdio.h>
#include<stdlib.h>
struct student_data
{
char *name;
int roll_num;
int marks;
void (* func_ptr)(struct student_data *ptr);
};
void print_data(struct student_data *ptr);
void print_data(struct student_data *ptr)
{
printf("\nNAME OF THE STUDENT %s", ptr -> name);
printf("\nROLL NUMBER OF STUDENT %d", ptr -> roll_num);
printf("\nMARKS OF STUDENT %d\n", ptr -> marks);
}
int main()
{
struct student_data *ptr;
ptr -> name = "ajish";
ptr -> roll_num = 2;
ptr -> marks = 50;
ptr -> func_ptr = &print_data;
func_ptr(ptr);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
func_ptr
是student_data
的成员,因此您必须使用struct Student_data *ptr
调用函数,该函数应该是指向结构实例的指针。例子:
func_ptr
is a member ofstudent_data
you have to call your function usingstruct student_data *ptr
which should be pointer to the instance of your struct.Example:
您需要将
main()
的右大括号之前的最后一行更改为更改
后,程序为我编译并运行。我用gcc 4.5.0编译。
您还应该
在堆上为
ptr
分配空间不要忘记在程序结束时释放它:
或者
声明
ptr
堆栈。这将要求您将
ptr
上的所有->
运算符更改为.
运算符。You need to change the last line before
main()
's closing brace fromto
After that change, the program compiled and ran for me. I compiled with gcc 4.5.0.
You should also either
Allocate space for
ptr
on the heapDon't forget to free it at the end of your program:
Or
Declare
ptr
on the stack.This will require you to change all your
->
operators onptr
to.
operators.