用C语言写一个结构体示例程序
该结构是不同数据类型变量的集合,在一个名称语法下组合在一起。
结构的声明和初始化
结构声明的一般形式如下-
datatype member1; struct tagname{ datatype member2; datatype member n; };
在这里,struct-关键字
tagname-指定结构名称
member1,member2-指定构成结构的数据项。
例子
struct book{ int pages; char author [30]; float price; };
结构变量
有三种声明结构变量的方法。它们如下-
1) struct book{ int pages; char author[30]; float price; }b; 2) struct{ int pages; char author[30]; float price; }b; 3) struct book{ int pages; char author[30]; float price; }; struct book b;
结构的初始化和访问
成员和结构变量之间的链接是使用成员运算符(或)点运算符建立的。
初始化可以通过以下方式完成-
方法一
struct book{ int pages; char author[30]; float price; } b = {100, “balu", 325.75};
方法二
struct book{ int pages; char author[30]; float price; }; struct book b = {100, “balu", 325.75};
方法三(使用成员运算符)
struct book{ int pages; char author[30]; float price; } ; struct book b; b. pages = 100; strcpy (b.author, “balu"); b.price = 325.75;
方法四(使用scanf函数)
struct book{ int pages; char author[30]; float price; } ; struct book b; scanf (“%d", &b.pages); scanf (“%s", b.author); scanf (“%f", &b. price);
我们可以在main方法中打印上述任一结构的内容,如下所示-
main ( ){ struct book b; clrscr ( ); printf ( "enter no of pages, author, price of book"); scanf ("%d%s%f", &b.pages, b.author, &b.price); printf("Details of book are"); printf("pages =%d, author = %s, price = %f", b.pages, b.author, b.price); getch(); }
例子
以下是结构的另一个例子-
#includestruct aaa{ struct aaa *prev; int i; struct aaa *next; }; main(){ struct aaa abc,def,ghi,jkl; int x=100; abc.i=0; abc.prev=&jkl; abc.next=&def; def.i=1; def.prev=&abc; def.next=&ghi; ghi.i=2;ghi.prev=&def; ghi.next=&jkl; jkl.i=3; jkl.prev=&ghi; jkl.next=&abc; x=abc.next->next->prev->next->i; printf("%d",x); }
输出
2