使用 C 語言編寫區域性作用域程式中的結構體
結構體是由不同資料型別變數的集合,這些變數組合在一起並使用一個名稱來標識。
結構體的特性
下面解釋了結構體的特性:
可以使用賦值運算子將不同資料型別的所有結構體元素的內容複製到另一個相同型別的結構體變數中。
對於處理複雜資料型別,最好在一個結構體中建立另一個結構體,這被稱為巢狀結構體。
可以將整個結構體、結構體的單個元素以及結構體的地址傳遞給函式。
還可以建立結構體指標。
結構體的宣告
結構體宣告的通用形式如下所示:
datatype member1; struct tagname{ datatype member2; datatype member n; };
這裡,**struct** 是關鍵字。
**tagname** 指定結構體的名稱。
**member1, member2** 是資料項。
例如:
struct book{ int pages; char author [30]; float price; };
示例
以下是區域性作用域結構體的 C 程式:
#include<stdio.h> struct{ char name[20]; int age; int salary; char add[30]; }emp1,emp2; int manager(){ struct{ char name[20]; int age; int salary; char add[50]; }manager ; manager.age=27; if(manager.age>30) manager.salary=65000; else manager.salary=55000; return manager.salary; } int main(){ printf("enter the name of emp1:"); //gets(emp1.name); scanf("%s",emp1.name); printf("
enter the add of emp1:"); scanf("%s",emp1.add); printf("
enter the salary of emp1:"); scanf("%d",&emp1.salary); printf("
enter the name of emp2:"); // gets(emp2.name); scanf("%s",emp2.name); printf("
enter the add of emp2:"); scanf("%s",emp2.add); printf("
enter the salary of emp2:"); scanf("%d",&emp2.salary); printf("
emp1 salary is %d",emp1.salary); printf("
emp2 salary is %d",emp2.salary); printf("
manager salary is %d",manager()); return 0; }
輸出
執行上述程式時,會產生以下結果:
enter the name of emp1:hari enter the add of emp1:hyderabad enter the salary of emp1:4000 enter the name of emp2:lucky enter the add of emp2:chennai enter the salary of emp2:5000 emp1 salary is 4000 emp2 salary is 5000 manager salary is 55000
廣告