Variable Length Arrays in C and C++

Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. C supports variable sized arrays from C99 standard. For example, the below program compiles and runs fine in C.

Also note that in C99 or C11 standards, there is feature called “flexible array members”, which works same as the above.

void fun(int n)
  int arr[n];
  // ......
int main()

But C++ standard (till C++11) doesn’t support variable sized arrays. The C++11 standard mentions array size as a constant-expression See (See 8.3.4 on page 179 of N3337). So the above program may not be a valid C++ program. The program may work in GCC compiler, because GCC compiler provides an extension to support them.

As a side note, the latest C++14 (See 8.3.4 on page 184 of N3690) mentions array size as a simple expression (not constant-expression).


//C program for variable length members in structures in GCC before C99.
//A structure of type student
struct student
   int stud_id;
   int name_len;
   int struct_size;
   char stud_name[0]; //variable length array must be last.
//Memory allocation and initialisation of structure
struct student *createStudent(struct student *s, int id, char a[])
    s = malloc( sizeof(*s) + sizeof(char) * strlen(a) );
    s->stud_id = id;
    s->name_len = strlen(a);
    strcpy(s->stud_name, a);
    s->struct_size = ( sizeof(*s) + sizeof(char) * strlen(s->stud_name) );
    return s;   
// Print student details
void printStudent(struct student *s)
  printf("Student_id : %d\n"
         "Stud_Name  : %s\n"
         "Name_Length: %d\n"
         "Allocated_Struct_size: %d\n\n",
          s->stud_id, s->stud_name, s->name_len, s->struct_size);
        //Value of Allocated_Struct_size here is in bytes.
//Driver Code
int main()
    struct student *s1, *s2;
    s1=createStudent(s1, 523, "Sanjayulsha");
    s2=createStudent(s2, 535, "Cherry");
    //size in bytes
    printf("Size of Struct student: %lu\n", sizeof(struct student));
    //size in bytes
    printf("Size of Struct pointer: %lu", sizeof(s1));
    return 0;


Student_id : 523
Stud_Name : Sanjayulsha
Name_Length: 11
Allocated_Struct_size: 23 

Student_id : 535
Stud_Name : Cherry
Name_Length: 6
Allocated_Struct_size: 18

Size of Struct student: 12
Size of Struct pointer: 8

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at #techcodebit #google #microsoft #facebook #interview portal #jobplacements


Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar