让我们编译和运行上面的程序,这将产生以下结果:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
结构体作为函数参数
可以传递一个结构作为函数的参数,非常类似传递任何其他变量或指针。访问可以象在上面的例子已经访问类似结构变量的方式:
#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 */
printBook( Book1 );
/* Print Book2 info */
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
指针结构
非常相似定义指针结构,来定义指向任何其他变量,如下所示:
struct Books *struct_yiibaier;
现在,可以存储结构变量的地址在上面定义的指针变量。为了找到一个结构变量的地址,将使用运算符&在结构体的名字之前,如下所示:
struct_yiibaier = &Book1;
访问使用一个指向结构的结构的成员,必须使用 -> 运算符如下:
struct_yiibaier->title;
让我们重新写上面的例子中使用结构指针,希望这将能够让我们更容易地理解概念:










