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

Thành viên mảng linh hoạt (Flexible Array Members) trong struct C


Thành viên mảng linh hoạt trong struct C nghĩa là khai báo mảng không kích thước trong struct, kích thước linh hoạt. Thành viên mảng linh hoạt phải là thành viên cuối cùng của lớp.

Ví dụ:

Ví dụ

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// cấu trúc employee, phải có ít nhất một thành viên khác ngoài thành viên mảng linh hoạt
struct employee {
    int emp_id;
    int name_len;
    int emp_size; // 'emp_size' lưu kích thước mảng ký tự linh hoạt emp_name[]
    char emp_name[]; // Thành viên mảng linh hoạt emp_name[] phải là thành viên cuối
};

struct employee *createEmployee(struct employee *e, int id, char a[]) {
    e = (struct employee *)malloc(sizeof(*e) + sizeof(char) * strlen(a)); // cấp phát bộ nhớ
    e->emp_id = id;
    e->name_len = strlen(a);
    // Gán kích thước theo emp_name là bản sao mảng a[] người dùng cung cấp
    strcpy(e->emp_name, a);
    return e;
}

void printEmployee(struct employee *e) { // in chi tiết nhân viên
    printf("Employee_id: %d\nEmployee Name: %s\nName Length: %d\n\n", e->emp_id, e->emp_name, e->name_len);
}

int main() {
    struct employee *e1 = createEmployee(e1, 26, "Ram");
    struct employee *e2 = createEmployee(e2, 53, "Madhu");
    printEmployee(e1);
    printEmployee(e2);
    printf("Size of structure Employee: %lu\n", sizeof(struct employee));
    return 0;
}

Kết quả

Employee_id: 26
Employee Name: Ram
Name Length: 3
Employee_id: 53
Employee Name: Madhu
Name Length: 5
Size of structure Employee: 12