struct union enum

本文详细介绍了C语言中结构体(struct)、联合(union)和枚举(enum)的基本用法及实例,包括结构体的定义、初始化、复制、链接,联合的数据共享特性,以及枚举类型的定义与应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 struct

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

#define SIZE 10

struct list{
	int value[10];
	struct list *next;
};

void struct_test(){
	struct list node1, node2;
	int i;
	for(i = 0; i < SIZE; i++)
		node1.value[i] = i;
	node1.next = NULL;

	node2 = node1;// = struct can help to copy array at a whole
	node1.next = &node2; //link

	for(i = 0; i < SIZE; i++){
		printf("%d\n", node1.next->value[i]);
		printf("%d\n", node2.value[i]);
	}
}

int main(){
	struct_test();
	return EXIT_SUCCESS;
}

2. union

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

union second_characteristic{
	char has_fur;
	short num_of_legs_in_excess_of_4;
};

struct creature{
	char has_backbone;
	union second_characteristic form;
};

void struct_union_test1(){
	struct creature dog, bug;
	dog.has_backbone = 1;
	dog.form.has_fur = 1;

	bug.has_backbone = 0;
	bug.form.num_of_legs_in_excess_of_4 = 8;

	printf("dog: has_backbone: %d, has_fur: %d\n",
			dog.has_backbone, dog.form.has_fur);
	printf("bug: has_backbone: %d, legs: %d\n",
			bug.has_backbone, bug.form.num_of_legs_in_excess_of_4);
}
//==============================
union bits32_tag{
	int whole;
	struct {char c0, c1, c2, c3;} byte;
};

void union_test2(){
	union bits32_tag value;
	value.byte.c0 = 255;
	value.byte.c1 = 255;
	value.byte.c2 = 255;
	value.byte.c3 = 127;
	printf("%d\n", value.whole);
}
//==============================
int main(){
	struct_union_test1();
	puts("=============");
	union_test2();
	return EXIT_SUCCESS;
}

3. enum

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

//in enum, element is seperated by ","
//the element can be accessed with name directly
enum weekday{
	ZERO, //start with 0
	ONE,
	TWO,
	THREE,
	FIVE = 5,
	SIX,
	NINE = 9
};

void enum_test(){
	printf("ZERO = %d\n", ZERO);
	printf("TWO = %d\n", TWO);
	printf("SIX = %d\n", SIX);
	printf("NINE = %d\n", NINE);
}

int main(){
	enum_test();
	return EXIT_SUCCESS;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值