结构体知识点

结构体的结构如下:

//关键字struct是数据类型说明符,指出下面说明的是结构体类型
struct 结构体名
{
	成员列表(可以是基本数据类型,指针,数组或其它结构体)
};//最后的分号不能少

结构体相当于自己设置了一种数据的类型,类型名即结构体的名字。
例如:

struct Student
{
	char s_id[8];
	char s_name[8];
	char s_sex[4];
	int s_age;
};

int main()
{
	int a = 10;
	int ar[10] = { 12,23,34,45 };
	//.c文件必须加struct,.cpp文件不需要struct
	struct Student stud1 = { "09001","yhping","man",23 };
	struct Student stud2 = { "yhping","man" };//与数组一样,没有赋值的地方初始化为0
	

	return 0;
}

结构体里面包含基础数据类型或其它结构体。
通过结构体变量名称访问结构体内部数据,用‘.’。
通过指针访问结构体内部数据,用‘->’。
结构体相当于另一种数据类型,所以同种不同名的结构体可以相互赋值。

struct Date
{
	int year;
	int month;
	int day;
};

struct Student
{
	char s_name[20];
	struct Date birthday;
	float score;
};
//结构体变量名访问就用"."
//指针变量访问就用"->"
int main()
{
	struct Student stud1 = { "yhping",2000,12,12,145.5 };
	struct Student stud2 = { "tulun",{2006,9,8},150.0 };
	struct Student stud3 = stud1;
	struct Student stud4 = {};

	stud4 = stud2;
	int year = stud1.birthday.year;

	struct Student* sp = &stud1;

	year = sp->birthday.year;

	return 0;
}

结构体内部不能嵌套自身,但可以嵌套结构体指针。

struct Student
{
	char s_id[12];
	char s_name[12];
	char s_sex[4];
	int s_age;

	//struct Student sx;   //形成了无限循环的生成结构体
	//因为无限生成结构体,所以无法测定结构体大小,所以称为不完整类型
	//struct Student *next;
	//因为生成指针不会引发下一层结构体定义,所以不会无限循环
};

int main()
{
	struct Student stud;
	return 0;
}

结构体变量名调用数据,通过指针调用数据。

struct Student
{
	char s_id[12];
	char s_name[14];
	char s_sex[6];
	int s_age;
};

int main()
{
	struct Student stud = { "09001","yhping","man",23 };
	struct Student* sp = &stud;

	int age1 = (*sp).s_age;    //*和.的优先级相同,但不加括号时,sp先和.相结合,不符合语法

	int age = stud.s_age;
	stud.s_age = 100;
	
	printf("%s %s %s %d\n", stud.s_id, stud.s_name, stud.s_sex, stud.s_age);

	char id[12];
	strcpy_s(id, 12, stud.s_id);
	stud.s_age = 12;
	strcpy_s(stud.s_id, 12, "09008");

	const char* s = "09008";
	s = "09009";//s是指针,指向的是"09008"的首地址,再转向"09009"的首地址。

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值