Variable Length Arrays in C and C++

CC++Server Side ProgrammingProgramming

Here we will discuss about the variable length arrays in C++. Using this we can allocate an auto array of variable size. In C, it supports variable sized arrays from C99 standard. The following format supports this concept −

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

But, in C++ standard (till C++11) there was no concept of variable length array. According to the C++11 standard, array size is mentioned as a constant-expression. So, the above block of code may not be a valid C++11 or below. In C++14 mentions array size as a simple expression (not constant-expression).

Example

Let us see the following implementation to get better understanding −

 Live Demo

#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);
}

Output

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
raja
Published on 27-Aug-2020 17:32:08
Advertisements