C语言:结构体与结构体指针

1.结构体简介

比如C语言的 数组 允许定义可存储相同类型数据项的变量,结构体是 C 编程中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。

结构体中的数据成员可以是基本数据类型(如 int、float、char 等),也可以是其他结构体类型、指针类型等。

2.结构体类型

struct 结构体名字{

    成员表列

} 变量;

(1)

//定义了一个结构体有标题Books,有定义的变量book
//将结构体里面的成员引用且赋值
struct Books
{
	char title[50];
	char author[50];
	char subject[100];
	int book_id;
} book;
int main()
{
	strcpy_s(book.title, "钢铁是怎样炼成的");
	strcpy_s(book.author, "小明");
	strcpy_s(book.subject, "文学");
	book.book_id = 0;
	printf("书名:%s\n", book.title);
	printf("作者:%s\n", book.author);
	printf("学科:%s\n", book.subject);
	printf("编号:%d\n", book.book_id);
	return 0;
}

/**********另外一种赋值方式
int main()
{
	book.title[0] = 1;
	book.author[0] = 2; 
	book.subject[0] = 3;
	book.book_id = 4;
	printf("书名:%d\n", book.title[0]);
	printf("作者:%d\n", book.author[0]);
	printf("学科:%d\n", book.subject[0]);
	printf("编号:%d\n", book.book_id);
	return 0;
}
*/

(2)

//定义了一个结构体无标题,有定义的变量s1,
// 这样这个结构体要定义其他成员的话,又要再写一遍,麻烦
//将结构体里面的成员引用且赋值
struct
{
	int a;
	char b;
	double c;
} s1;
int main()
{
	s1.a = 1;
	s1.b = 2;
	s1.c = 3;
	printf("%d\n", s1.a);
	printf("%d\n", s1.b);
	printf("%f\n", s1.c);
	return 0;
}

(3)

//定义了一个结构体有标题,无定义的变量,需要单独在声明变量
//将结构体里面的成员引用且赋值
struct SIMPLE
{
	int a;
	char b;
	double c;
};
struct SIMPLE index;
int main()
{
	index.a = 1;
	index.b = 2;
	index.c = 3;

	printf("%d\n", index.a);
	printf("%d\n", index.b);
	printf("%f\n", index.c);
	return 0;
}

(4)

//也可以用typedef创建新类型;typedef好处就是好看
typedef struct
{
	int a;
	char b;
	double c;
} Simple2;
//现在可以用Simple2作为类型声明新的结构体变量
 Simple2 index , u2[20] , *u3;
int main()
{
	index.a = 1;
	index.b = 2;
	index.c = 3;

	printf("%d\n", index.a);
	printf("%d\n", index.b);
	printf("%f\n", index.c);

	u2[0].a = 4;
	u2[0].b = 5;
	u2[0].c = 6;

	printf("%d\n", u2[0].a);
	printf("%d\n", u2[0].b);
	printf("%f\n", u2[0].c);

	u3 = &index;
	u3->a = 10;
	u3->b = 20;
	u3->c = 30;
	//用结构体指针访问结构体变量成员的第一种形式
	printf("%d\n", u3->a);
	printf("%d\n", u3->b);
	printf("%f\n", u3->c);
	//用结构体指针访问结构体变量成员的第二种形式
	printf("%d\n", (*u3).a);
	printf("%d\n", (*u3).b);
	printf("%f\n", (*u3).c);

	//已经改变指向结构体成员的数据了
	printf("%d\n", index.a);
	printf("%d\n", index.b);
	printf("%f\n", index.c);

	return 0;
}

注:内容参考C 结构体 | 菜鸟教程 (runoob.com)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值