C语言初学10:结构体

一、结构体定义

struct tag{  //结构体标签
	member-list;  //变量定义
	member-list;
	...
} variable-list; //结构体变量,可以指定一个或多个结构变量

1.1 结构体没有标签

struct {  
	int a;  //变量定义
	char b;
	double c;
} s1; //结构体变量

1.2 结构体没有变量

struct SIMPLE{ //结构体标签 
	int a;  //变量定义
	char b;
	double c;
};
#include <stdio.h>
#include <string.h>
 
struct Books
{
   char  title[50];
};
 
int main( )
{
	struct Books book1; /* 声明book1,类型为Books*/
	
    strcpy( book1.title, "C 教程");
    printf( "书标题 : %s\n", book1.title);
    return 0;
}

 

1.3 typedef创建新类型

typedef struct //结构体标签
{  
	int a;  //变量定义
	char b;
	double c;
} Simple2;
// 使用Simple2作为类型声明新的结构体变量
Simple2 u1,u2[20],*u3;

二、结构体变量的初始化

#include <stdio.h>

struct Books
{
	char title[50];
	char author[50];
	char subject[100];
	int book_id;
} book = {"c 语言", "RUNOOB" ,"编程语言", 12345};

int main()
{
	printf("title:%s\nauthor:%s\nsubject:%s\nbook_id:%d\n",
	book.title,book.author,book.subject,book.book_id);
}

三、访问结构体成员

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

struct Books  //使用 struct 关键字来定义结构类型的变量
{
	char title[50];
	char author[40];
	char subject[100];
	int book_id;
} book;

int main()
{
	strcpy(book.title,"C 教程");  //使用成员访问运算符(.)访问结构的成员
	strcpy(book.author,"Runoob");
	strcpy(book.subject,"编程语言");
	book.book_id = 123;
	
	printf( "书标题 : %s\n", book.title);
	printf( "书作者 : %s\n", book.author);
    printf( "书类目 : %s\n", book.subject);
	printf( "书 ID : %d\n", book.book_id);
	return 0;
}

执行结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值