C语言结构体

1. C语言结构体初始化的三种方法

转载自:https://blog.csdn.net/chinaeran/article/details/44755759

https://blog.csdn.net/ericbar/article/details/79567108

直接上示例

#include <stdio.h>
 
struct student_st
{
	char c;
	int score;
	const char *name;
};
 
static void show_student(struct student_st *stu)
{
	printf("c = %c, score = %d, name = %s\n", stu->c, stu->score, stu->name);
}
 
int main(void)
{
	// method 1: 按照成员声明的顺序初始化
	struct student_st s1 = {'A', 91, "Alan"};
	show_student(&s1);
 
	// method 2: 指定初始化,成员顺序可以不定,Linux 内核多采用此方式
	struct student_st s2 = 
	{
		.name = "YunYun",
		.c = 'B',
		.score = 92,
	};
	show_student(&s2);
 
	// method 3: 指定初始化,成员顺序可以不定
	struct student_st s3 = 
	{
		c: 'C',
		score: 93,
		name: "Wood",
	};
	show_student(&s3);
	
	return 0;
}

运行结果

如果想初始化结构体数组,可采用 {{ }, { }, { }} 方式,如

struct student_st stus[2] = 
{
	{
		.c = 'D',
		.score = 94,
		/*也可以只初始化部分成员*/
	},
	{
		.c = 'D',
		.score = 94,
		.name = "Xxx"
	},
};

2. 结构体中嵌入联合体

结构体中可以嵌入匿名联合体,如下:

可以直接使用联合体的成员。

https://blog.csdn.net/npy_lp/article/details/7038214

https://blog.csdn.net/openblog/article/details/7548363

#include <stdio.h>

typedef struct 
{
	int age;
        //int a;//重复定义,报错
	union
	{
		int a;
		char b;
	};
	char name[10];	
}STUDENT_T;

int main(int argc, char const *argv[])
{
	STUDENT_T student;
	student.age = 10;
	student.a = 65;
	printf("student.a = %d\n",student.a);
	return 0;
}

当然结构体中就不能再重复定义相同的变量了,不然会报错:

使用普通的联合体:

#include <stdio.h>

typedef struct 
{
	int age;
	union
	{
		int a;
		char b;
	}test;
	char name[10];	
}STUDENT_T;

int main(int argc, char const *argv[])
{
	STUDENT_T student;
	student.age = 10;
	student.test.a = 65;
	printf("student.a = %d\n",student.test.a);
	return 0;
}

 

这个时候在结构体中就不能直接访问到联合体的成员了,需要通过联合体访问。

3. C语言结构体变量名含义

https://bbs.csdn.net/topics/391867291?page=1 

今天突然在想,C语言结构体名含义是啥,是结构体地址么,类似数组名那样?当然不是,那还要对结构体取地址干啥。看了网友的评论,豁然开朗。结构体变量名,其实就代表一个普通的变量名称,和int a中的变量a一样,只不过a的值可以直接通过printf函数输出,而结构体的值不能直接通过printf输出,试想如果要直接输出结构体的值,用什么格式符号%d?%s?都不行。所以,它就仅仅是一个变量名而已,不用纠结。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值