Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Viết chương trình struct trong phạm vi cục bộ (local scope) bằng C


Struct (cấu trúc) là tập hợp các biến khác kiểu dữ liệu, nhóm lại dưới một tên duy nhất.

Đặc điểm của struct

  • Có thể sao chép toàn bộ phần tử struct sang biến struct khác cùng kiểu bằng toán tử gán.
  • Để xử lý kiểu dữ liệu phức tạp, có thể tạo struct lồng nhau (nested struct).
  • Có thể truyền toàn bộ struct, từng phần tử hoặc địa chỉ struct cho hàm.
  • Có thể tạo con trỏ struct.

Khai báo struct

Dạng chung:

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

struct là từ khóa. tagname là tên struct. member1, member2 là các mục dữ liệu.

Ví dụ:

struct book{     int pages;     char author [30];     float price; };

Ví dụ

Chương trình C struct trong phạm vi cục bộ:

#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("\nenter the add of emp1:");     scanf("%s",emp1.add);     printf("\nenter the salary of emp1:");     scanf("%d",&emp1.salary);     printf("\nenter the name of emp2:");     // gets(emp2.name);     scanf("%s",emp2.name);     printf("\nenter the add of emp2:");     scanf("%s",emp2.add);     printf("\nenter the salary of emp2:");     scanf("%d",&emp2.salary);     printf("\nemp1 salary is %d",emp1.salary);     printf("\nemp2 salary is %d",emp2.salary);     printf("\nmanager salary is %d",manager());     return 0; }

Kết quả

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