一、结构体定义
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;
}
执行结果: