여기에서는 C++의 가변 길이 배열에 대해 설명합니다. 이것을 사용하여 가변 크기의 자동 배열을 할당할 수 있습니다. C에서는 C99 표준의 가변 크기 배열을 지원합니다. 다음 형식은 이 개념을 지원합니다 -
void make_arr(int n){
int array[n];
}
int main(){
make_arr(10);
} 그러나 C++ 표준(C++11까지)에는 가변 길이 배열이라는 개념이 없었습니다. C++11 표준에 따르면 배열 크기는 상수 표현식으로 언급됩니다. 따라서 위의 코드 블록은 유효한 C++11 이하가 아닐 수 있습니다. C++14에서는 배열 크기를 상수 표현식이 아닌 단순 표현식으로 언급합니다.
예시
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
#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);
} 출력
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