📜  C和C++中的可变长度数组

📅  最后修改于: 2021-05-30 19:10:49             🧑  作者: Mango

可变长度数组是一项功能,我们可以在其中分配可变大小的自动数组(在堆栈上)。 C支持C99标准的可变大小数组。例如,以下程序可以在C中编译并正常运行。

还要注意,在C99或C11标准中,有一个称为“柔性阵列成员”的功能,与上述功能相同。

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

但是C++标准(直到C++ 11)不支持可变大小的数组。 C++ 11标准提到数组大小是一个常量表达式,请参见(请参见N3337的第8.3.4页的第8.3.4节)。因此,以上程序可能不是有效的C++程序。该程序可能在GCC编译器中工作,因为GCC编译器提供了扩展来支持它们。

附带说明一下,最新的C++ 14(请参见N3690的第184页的8.3.4)提到数组大小是一个简单的表达式(不是常量表达式)。

执行

//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;
}

输出:

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

参考:
http://stackoverflow.com/questions/1887097/variable-length-arrays-in-c
https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。