使用C语言编写一个关于结构的示例程序

使用c语言编写一个关于结构的示例程序

The structure is a collection of different datatype variables, grouped together under a single name Syntax.

Declaration and initialization of structures

The general form of structure declaration is as follows −

datatype member1;struct tagname{   datatype member2;   datatype member n;};

在这里,struct – 关键字

         tagname – 指定结构的名称

立即学习“C语言免费学习笔记(深入)”;

         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;

结构的初始化和访问

成员和结构变量之间的链接是通过成员运算符(或者点运算符)建立的。

初始化可以通过以下方式进行:

方法1

struct book{   int pages;   char author[30];   float price;} b = {100, “balu", 325.75};

Method 2

struct book{   int pages;   char author[30];   float price;};struct book b = {100, “balu", 325.75};

Method 3 (using member operator)

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);

We can print the contents of either of the above structures in the main method as shown below −

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();}

Example

Following is another example of structures −

 Live Demo

#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

以上就是使用C语言编写一个关于结构的示例程序的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1443768.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 20:33:31
下一篇 2025年12月8日 05:28:14

发表回复

登录后才能评论
关注微信