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

Mảng chiều dài biến đổi (VLA) trong C và C++


Thảo luận về mảng chiều dài biến đổi (Variable Length Arrays - VLA) trong C++. Cho phép cấp phát mảng tự động kích thước biến đổi. Trong C, hỗ trợ VLA từ chuẩn C99. Định dạng sau hỗ trợ:

void make_arr(int n) {
    int array[n];
}
int main() {
    make_arr(10);
}

Nhưng trong chuẩn C++ (tính đến C++11) không có khái niệm VLA. Theo C++11, kích thước mảng phải là constant-expression. Do đó đoạn code trên có thể không hợp lệ C++11 trở xuống. C++14 cho phép array size là simple expression (không bắt buộc constant-expression).

Ví dụ

Triển khai để hiểu rõ hơn:

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class employee {
public:
    int id;
    int name_length;
    int struct_size;
    char emp_name[0];
};
employee* make_emp(struct employee* e, int id, char arr[]) {
    e = new employee();
    e->id = id;
    e->name_length = strlen(arr);
    strcpy(e->emp_name, arr);
    e->struct_size = (sizeof(*e) + sizeof(char) * strlen(e->emp_name));
    return e;
}
void disp_emp(struct employee* e) {
    cout << "Emp Id:" << e->id << endl;
    cout << "Emp Name:" << e->emp_name << endl;
    cout << "Name Length:" << e->name_length << endl;
    cout << "Allocated:" << e->struct_size << endl;
    cout << "---------------------------------------" << endl;
}
int main() {
    employee *e1, *e2;
    e1 = make_emp(e1, 101, "Jayanta Das");
    e2 = make_emp(e2, 201, "Tushar Dey");
    disp_emp(e1);
    disp_emp(e2);
    cout << "Size of student: " << sizeof(employee) << endl;
    cout << "Size of student pointer: " << sizeof(e1);
}

Kết quả

Emp Id:101
Emp Name:Jayanta Das
Name Length:11
Allocated:23
---------------------------------------
Emp Id:201
Emp Name:Tushar Dey
Name Length:10
Allocated:22
---------------------------------------
Size of student: 12
Size of student pointer: 8