C语言中的结构体的入门学习教程

2020-01-06 14:15:01于丽


#include <stdio.h>
#include <string.h>
 
struct Books
{
  char title[50];
  char author[50];
  char subject[100];
  int  book_id;
};

/* function declaration */
void printBook( struct Books *book );
int main( )
{
  struct Books Book1;    /* Declare Book1 of type Book */
  struct Books Book2;    /* Declare Book2 of type Book */
 
  /* book 1 specification */
  strcpy( Book1.title, "C Programming");
  strcpy( Book1.author, "Nuha Ali"); 
  strcpy( Book1.subject, "C Programming Tutorial");
  Book1.book_id = 6495407;

  /* book 2 specification */
  strcpy( Book2.title, "Telecom Billing");
  strcpy( Book2.author, "Zara Ali");
  strcpy( Book2.subject, "Telecom Billing Tutorial");
  Book2.book_id = 6495700;
 
  /* print Book1 info by passing address of Book1 */
  printBook( &Book1 );

  /* print Book2 info by passing address of Book2 */
  printBook( &Book2 );

  return 0;
}
void printBook( struct Books *book )
{
  printf( "Book title : %s
", book->title);
  printf( "Book author : %s
", book->author);
  printf( "Book subject : %s
", book->subject);
  printf( "Book book_id : %d
", book->book_id);
}

让我们编译和运行上面的程序,这将产生以下结果:


Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

位字段
位字段允许数据在一个结构体包装。这是特别有用的,当内存或存储数据非常宝贵。典型的例子:

包装几个对象到一个机器语言。例如1位标志能够压缩长度

读取外部的文件格式 - 非标准的文件格式可以读出。例如: 9位整数。

C语言允许我们通过结构定义:bit 长度的变量之后。例如:


struct packed_struct {
 unsigned int f1:1;
 unsigned int f2:1;
 unsigned int f3:1;
 unsigned int f4:1;
 unsigned int type:4;
 unsigned int my_int:9;
} pack;

在这里,packed_struct包含6个成员:四个1位标志s f1..f3, 一个 4 位类型和9位my_int。

C语言自动包装上述位字段尽可能紧凑,条件是字段的最大长度小于或等于计算机的整数字长。如果不是这种情况,那么一些编译器可以允许,而其他将重叠存储在下一个字段的存储器。

指针和数组:
这是永远绕不开的话题,首先是引用: