首頁  >  文章  >  後端開發  >  使用C語言編寫一個關於結構的範例程序

使用C語言編寫一個關於結構的範例程序

王林
王林轉載
2023-08-27 12:01:18797瀏覽

使用C語言編寫一個關於結構的範例程序

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

Declaration and initialization of structures

##The gene

Declaration and initialization of structures##ral##The gene

of structure declaration is as follows −

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

在這裡,struct - 關鍵字

         tagname - 指定結構的名稱

         member1, member2 -

#         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

#include<stdio.h>
struct 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
#### Live Demo###rrreee###輸出###

以上是使用C語言編寫一個關於結構的範例程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除