Định nghĩa cấu trúc trong C
Từ khóa struct được sử dụng để xác định cấu trúc. Hãy xem cú pháp để định nghĩa cấu trúc trong C.
struct structure_name { data_type member1; data_type member2; ... data_type memeberN;};Ví dụ :
struct employee { int id; char name[50]; float salary;};
Khai báo biến cấu trúc
Có hai cách để khai báo biến cấu trúc:
- Sử dụng từ khóa struct trong hàm main().
- Khai báo biến tại thời điểm định nghĩa cấu trúc.
1. Cách 1
Khai báo biến cấu trúc bên trong hàm main(), ví dụ:
struct employee { int id; char name[50]; float salary;}; int main() { struct employee a1, a2;}
1. Cách 2
Khai báo biến cấu trúc tại thời điểm định nghĩa cấu trúc, ví dụ:
struct employee { int id; char name[50]; float salary;} a1, a2;Truy cập các thành viên của cấu trúc
Có hai cách để truy cập vào các thành viên cấu trúc:
- Bởi . (thành viên hoặc toán tử chấm).
- Bởi -< (toán tử con trỏ cấu trúc).
Ví dụ: Truy cập dùng toán tử chấm.
e1.id = 17;e1.name = "Anh";e1.salary = 1000;Ví dụ truy cập dùng con trỏ.
struct employee *pdata,a1;
*pdata=&a1;
pdata->id=17;
pdata->salary=1000;
Ví dụ cấu trúc (structure) trong C
Ví dụ 1: lưu trữ thông tin của một employee.
#include<stdio.h>#include <string.h>struct employee { int id; char name[50]; float salary;} e1; // khai bao bien e1int main() { // luu tru thong tin employee e1.id = 17; strcpy(e1.name, "AnhTran"); // sao chep string thanh mang char e1.salary = 1000; // hien thi thong tin employee ra man hinh printf("employee 1 id : %d\n", e1.id); printf("employee 1 name : %s\n", e1.name); printf("employee 1 salary : %f\n", e1.salary); return 0;}IN RA :
employee 1 id : 17
employee 1 name : Anh Tran
employee 1 salary : 1000.000000
#include<stdio.h>
#include <string.h>
struct nhanvien {
int age;
int w;
};
int main()
{
struct nhanvien *pdata,e1;
// dung con tro struct.
pdata=&e1;
pdata->age =15;
pdata->w=30;
printf(" Struct to pointer :value truct is %d age, and %d w \n",pdata->age,pdata->w);
// dung toan tu cham
e1.age=30;
e1.w=65;
printf(" Struct access by (.) value truct is %d age, and %d w \n",e1.age,e1.w);
}
IN RA :
Struct to pointer :value truct is 15 age, and 30 w
Struct access by (.) value truct is 30 age, and 65 w