C语言之结构体

#include<stdio.h>

//结构体类型的定义
//定义一个学生结构体类型。用于存放学生的信息
//这仅仅是一个类型
struct Student {
	char *name;
	int age;
	float height;
};

int main() {

	//————————————————————————————定义结构体变量——————————————————————————————
	//第一种方式
	struct Student stu1;
	long size = sizeof(stu1);	//或者sizeof(struct Student;
	printf("%ld
",size);
	printf("%ld
",sizeof(char *) + sizeof(int) + sizeof(float));
	//sizeof(stu1) = sizeof(char *) + sizeof(int) + sizeof(float)

	//另外一种方式:创建结构体的时候同一时候创建结构体变量
	struct Stu {
		char *name;
		int age;
	}stu2;


	//第三种方式:
	struct {
		int a;
		float b;
	}stu3,stu4;


	//注意点:
	/*
	1.错误,不能够在结构体中创建本结构体的结构体变量
	struct Stud {
		int age;
		char *name;
		struct Stud st;
	};*/

	// 2.结构体中内部能够包括其它的结构体
	struct Stud {
		int age;
		char *name;
		struct Stu st;
	};
	//3.在未定义结构体变量的时候,结构体类型不占内存空间(不会开辟内存)

	//————————————————————————————定义结构体变量——————————————————————————————
	struct Stu1 {
		int age;
		char *name;
		float height;
	};

	//方式一:
	struct Stu1 su;	//定义结构体变量
	su.age =13;
	su.name = "jack";
	su.height = 1.78;
	printf("age:%d   name:%s  height:%.2f
",su.age,su.name,su.height);

	//方式二:
	struct Stu1 su1 = {15,"Tom",1.67};
	printf("age:%d   name:%s  height:%.2f
",su1.age,su1.name,su1.height);

	// struct Stu1 su2;
	// su2 = {15,"Tom",1.67};   错误



	return 0;
}

原文地址:https://www.cnblogs.com/yxysuanfa/p/6763611.html