c语言入门教程–-17结构体

195 阅读1分钟

c语言入门教程–-17结构体

用 struct 声明
方法1
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

方法2
struct
{
int a;
char b;
double c;
} S;

S s;

//我们可以将S看做一个类型,像一个int一样所以S s;这就是一个声明

s. a
s.b
s.c
这些就可以当做正常的变量使用。

我们还可以声明结构体数组
S s[5];

s[0]. a
s[0].b
s[0].c

例子:

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

struct Books
{
   char  title[50];
   char  author[50];
   int   book_id;
} book;

int main ()
{
   gets(book.title); 
   gets(book.author); 
   scanf("%d",&book.book_id);
   
   printf("书名:%s\n",book.title);
   printf("作者:%s\n",book.author);
   printf("图书编号:%d\n",book.book_id);
    
   return 0;
}

运行结果:
在这里插入图片描述
在上面的例子,我们可以看出我们把书比作一个整体,然后书里面有书名,作者,图书编号等属性。
以后类似这样的事物,我们都可以用结构体来表示。