C语言结构体全通详解

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

struct student
{
	int num;
	char *tel;
	int *can;
};

struct test_pfun {
	int id;
	char name[10];
	int *age;
	struct student stu;
	struct student *pstu;
	int (*add) (int a,int b);
	int (*sub) (int a,int b);
	int (*mult) (int a,int b);
};

static int  test_add(int a,int b)
{
  	return (a+b);
}

static int  test_sub(int a,int b)
{
  	return (a-b);
}

static int   test_mult(int a,int b)
{
 	 return (a*b);
}


void print_uage(char *p)
{
	printf("%s <num1> <num2>\n ",p);
}

int cnt ,cnt1;

struct student zhang = {
	.num = 2013,
	.tel    ="114",
	.can  = &cnt,
};

struct student zhang1 = {
	.num = 2014,
	.tel    ="120",
	.can  = &cnt1,
};

 int main(int argc,char **argv)
{
	int a ,b; 

	struct test_pfun google[] = {
		[0] = {                       			 /* [0] is omissible */
				google[0].id = 10,         /* google[0] is omissible */
				.name = "google",
				.sub   =test_sub,
				.mult  =test_mult,
				.age 	= &b,
				.pstu    = &zhang,
				.stu={
					.num = 258,
					.tel   =  "110",
				},
		},
		{
			.id 		= 11,
			.name 	= "linux",
			.age 	= &a,
			.add   	=test_add,
			.pstu    = &zhang1,
			.stu 		={
			.num = 256,
			.tel = "119",
			},

		},
	
	} ;

	if(argc!=3)
	{
		print_uage(argv[0]);
		return -1;
	}

	a=strtoul(argv[1],NULL,0);
	b=strtoul(argv[2],NULL,0);
	printf("a = %d b= %d \n",a,b);
	printf("a+b=%d\n",google[1].add(a,b));
	printf("a-b=%d\n",google[0].sub(a,b));
	printf("a*b=%d\n",google[0].mult(a,b));
	
	printf("google[0].id  = %d google[1].id  = %d\n",google[0].id ,google[1].id );
	printf("google[0].age = %d google[1].age = %d\n",*google[0].age ,*google[1].age);
	printf("google[0].name = %s google[1].name = %s\n",google[0].name ,google[1].name);

	printf("google[0].stu.num = %d google[0].stu.tel =%s\n",google[0].stu.num,google[0].stu.tel);
	printf("google[1].stu.num = %d google[1].stu.tel =%s\n",google[1].stu.num,google[1].stu.tel);

	printf("google[0].pstu->num = %d google[0].pstu->tel =%s  google[0].pstu->can =%d\n",google[0].pstu->num,google[0].pstu->tel,*google[0].pstu->can);
	printf("google[1].pstu->num = %d google[1].pstu->tel =%s  google[1].pstu->can =%d\n ",google[1].pstu->num,google[1].pstu->tel,*google[0].pstu->can);


	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_21792169/article/details/78034385