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

Truy cập con trỏ Structure trong C


Con trỏ structure lưu địa chỉ của structure. Truy cập thành viên bằng toán tử ->.

Khai báo & Truy cập

struct ten *ptr;
ptr->thanh_vien;

Ví dụ 1: Truy cập mảng trong structure qua con trỏ

#include <stdio.h>
struct classroom {
    int students[7];
};
int main() {
    struct classroom clr = {2, 3, 5, 7, 11, 13};
    int *ptr = (int *)&clr;
    printf("%d\n", *(ptr + 4)); // phần tử index 4 = 11
    return 0;
}

Kết quả

11

Giải thích: ptr trỏ đến phần tử đầu (2). *(ptr+4) truy cập phần tử thứ 5 (index 4) = 11.

Ví dụ 2: Con trỏ structure sinh viên

#include <stdio.h>
struct student {
    int sno;
    char sname[30];
    float marks;
};
int main() {
    struct student s;
    struct student *st;
    printf("Nhap sno, ten, diem: ");
    scanf("%d %s %f", &s.sno, s.sname, &s.marks);
    st = &s;
    printf("\nThong tin:\n");
    printf("Ma so = %d\n", st->sno);
    printf("Ten   = %s\n", st->sname);
    printf("Diem  = %.2f\n", st->marks);
    return 0;
}

Kết quả

Nhap sno, ten, diem: 1 bhanu 69
Thong tin:
Ma so = 1
Ten   = bhanu
Diem  = 69.00