What is 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()
{
fun(6);
}

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).

Implementation

//C program for variable length members in structures in GCC before C99.
#include
#include
#include

//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");
	
	printStudent(s1);
	printStudent(s2);
	
	//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;
}

Output:

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

 

Submit Your Programming Assignment Details