可变长度数组也称为 运行时大小 或 可变大小 数组。这种数组的大小是在运行时定义的。
null
可变修改类型包括可变长度数组和指向可变长度数组的指针。可变更改的类型必须在块范围或函数原型范围内声明。
可变长度数组是一种功能,我们可以在其中分配可变大小的自动数组(在堆栈上)。它可以在typedef语句中使用。C支持C99标准中的可变大小阵列。例如,下面的程序在C语言中编译并运行良好。
void fun(int n){ int arr[n]; // ......} int main(){ fun(6);}
注: 在里面 C99 或 C11 根据标准,有一个功能叫做 灵活的数组成员 ,其工作原理与上述相同。
但是C++标准(直到C++ 11)不支持可变大小的数组。C++11标准提到数组大小是一个常量表达式。所以上面的程序可能不是一个有效的C++程序。该程序可以在GCC编译器中工作,因为GCC编译器提供了一个扩展来支持它们。 作为补充,最新的 C++14 提到数组大小是一个简单的表达式(不是常量表达式)。 实施
C
// 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 : %d" "Stud_Name : %s" "Name_Length: %d" "Allocated_Struct_size: %d" , 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" , sizeof ( struct student)); // size in bytes printf ( "Size of Struct pointer: %lu" , sizeof (s1)); return 0; } |
输出
Student_id : 523Stud_Name : SanjayulshaName_Length: 11Allocated_Struct_size: 23Student_id : 535Stud_Name : CherryName_Length: 6Allocated_Struct_size: 18Size of Struct student: 12Size of Struct pointer: 8
本文由 阿比拉蒂 和 桑杰·坎纳 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END