C语言程序设计之结构体中定义函数的使用方法

C语言中的结构体里面是不能直接定义函数的,但是可以用函数指针来实现。具体方法如下:

struct data
{
	char *word;
	void (*display)(char *p);
};

完整代码如下:

#include <stdio.h>
#include <stdlib.h>

struct data
{
	char *word;
	void (*display)(char *p);
};

void print(char *p)
{
	printf("%s\n", p);
}

int main(void)
{
	/* No.1 */
	struct data d1 = {"Hello World", print};
	d1.display(d1.word);
	
	/* No.2 */
	struct data d2 = {.word = "Hello World", .display = print};
	d2.display(d2.word);
	
	/* No.3 */
	struct data *dp = malloc(sizeof(struct data));
	dp->word = "Hello World";
	dp->display = print;
	dp->display(dp->word);
	free(dp);
	
	return 0;	
}

Leave a Reply

Your email address will not be published. Required fields are marked *