5-结构联合

1-结构体概念.c

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

struct Student     //Student结构体名   结构体声明
{
	int id;
	char name[32];
	char sex;
};
typedef struct Student stu;

int main()
{
	struct Student s1;      //定义结构体变量
	struct Student s2 = {2, "jack", 'm'};
	stu s3 = {3, "tim", 'm'};

	//s1 = {1, "jason", 'f'};

	s1.id = 1;
	strcpy(s1.name, "jason");
	s1.sex = 'f';

	printf("%d %s %c\n", s1.id, s1.name, s1.sex);
	printf("%d %s %c\n", s2.id, s2.name, s2.sex);

	stu *ps = (stu *)malloc(sizeof(stu) * 1);
	ps->id = 4;
	strcpy(ps->name, "lily");
	ps->sex = 'f';

	printf("%d %s %c\n", ps->id, ps->name, ps->sex);

	//stu s4[5] = {0};     //结构体数组,数组每个元素都是结构体
	stu s4[5] = {{5, "aaa", 'm'}, {6, "bbb", 'f'}};
	int i;
	for (i = 0; i < 2; i++)
	{
		printf("%d %s %c\n", s4[i].id, s4[i].name, s4[i].sex);
	}

	stu *ps1[5] = {0};    //结构体指针数组

	return 0;
}


2-结构体长度.c

```#include <stdio.h>

//1、结构体的总长度一定是最长成员的整数倍
//2、每个成员的偏移量一定是该成员长度的整数倍

struct T
{
	int x;
	char y;
};
struct Test
{
	char c[10];
	short a;
	float b;
	struct T t;
	char d;
};

int main()
{
	printf("%lu\n", sizeof(struct Test));
	return 0;
}

3-联合体.c

```c
#include <stdio.h>

//所有成员共享同一块内存
union Test
{
	int a;
	int b;
	char c;
};

union Byte
{
	short val;
	char ch[sizeof(short)];
};

int main()
{
	union Test t1;
	t1.a = 100;
	printf("t1.b = %d\n", t1.b);
	t1.a = 0x10101010;
	printf("t1.c = %x\n", t1.c);

	union Byte b;
	b.val = 0x0102;
	if (b.ch[0] == 2 && b.ch[1] == 1)
	{
		printf("小端字节序\n");
	}
	else if (b.ch[1] == 2 && b.ch[0] == 1)
	{
		printf("大端字节序\n");
	}

	//怎样进行大小端的转换

	return 0;
}

4-枚举.c

#include <stdio.h>

/*#define A 0
#define B 1
#define C 2
#define D 3*/

enum Num
{
	A,
	B,
	C = 1000,
	D
};

int main()
{
	printf("%d\n", A);	
	printf("%d\n", B);	
	printf("%d\n", C);	
	printf("%d\n", D);	

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值