ในที่นี้เราจะพูดถึงอาร์เรย์ความยาวผันแปรใน 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