用户可以定义指向结构的指针,方式与定义指向其他类型变量的指针相似,如下所示
struct Books *struct_pointer;
可以在上述定义的指针变量中存储结构变量的地址,为了查找结构变量的地址,请把&运算符放在结构名称前,如下所示
struct_pointer=&Book1;
为了使用指向该结构的指针访问结构的成员,用户必须使用->运算符,如下所示
struct_pointer->title;
实例
#include <iostream>
#include <cstring>
using namespace std;
void printBook(struct Books *book);
struct Books
{
char title [50];
char author [50];
char subject [100];
int book_id;
};
int main()
{
struct Books Book1;
struct Books Book2;
strcpy (Book1.title,"1");
strcpy (Book1.author,"2")
strcpy (Book1.subject,"3");
Book1.book_id=7;
strcpy (Book2.title,"4");
strcpy (Book2.author,"5")
strcpy (Book2.subject,"6");
Book1.book_id=8;
printBook(&Book1);printBook(&Book2);
return 0;
}
void printBook(struct Books book)
{
cout<<"book title:"<<book.title<<endl;
cout<<"book author:"<<book.author<<endl;
cout<<"book subject:"<<book.subject<<endl;
cout<<"book id:"<<book.book_id<<endl;
}
显示结果book title :1
book author:2
book subject:3
book id:7
book title :4
book author:5
book subject:6
book id:8