可变长度数组也称为运行时大小或可变大小数组。这种数组的大小是在运行时定义的。
可变修改类型包括可变长度数组和指向可变长度数组的指针。可变更改的类型必须在块范围或函数原型范围内声明。
可变长度数组是一项功能,我们可以在其中分配可变大小的自动数组(在堆栈上)。它可以在 typedef 语句中使用。C 支持来自 C99 标准的可变大小数组。例如,下面的程序在 C 中编译并运行良好。
注意:在C99或C11标准中,有一个称为灵活数组成员的功能,其工作原理与上述相同。
但是 C++ 标准(直到 C++11)不支持可变大小的数组。C++11 标准将数组大小作为常量表达式提及。所以上面的程序可能不是一个有效的 C++ 程序。该程序可以在 GCC 编译器中运行,因为 GCC 编译器提供了一个扩展来支持它们。
附带说明一下,最新的C++14 将数组大小作为一个简单的表达式(不是常量表达式)。
执行
输出
void fun(int n)
{
int arr[n];
// ......
}
int main()
{
fun(6);
}
// C program for variable length members in structures in
// GCC before C99
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 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 : %dn"
"Stud_Name : %sn"
"Name_Length: %dn"
"Allocated_Struct_size: %dnn",
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: %lun",
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