0長數組介紹:也叫柔性數組
用途:為了滿足需要變長度的結構體
用法:在一個結構體的最后,申明一個長度為0的數組,就可以實現這個結構體長度的可變,如:
typedef struct _Student
{
int Age;
int Length;
char Info[0];//0長數組
}Student,*pStudent;
說明:
1、長度為0的數組並不占用空間,sizeof(Student)=8。
2、它只是一個偏移量,數組名這個符號本身代表了一個不可修改的地址常量。
優缺點:
優點:比起在結構體中聲明一個指針變量,再進行動態分配的辦法,這種方法效率要高,因為在訪問數組內容時,不需要間接訪問,避免了兩次訪存。
缺點:在結構體中,為0的數組必須在最后聲明,使用上有一定限制。
例子:
#include <QApplication>
#include <QDebug>
#include <QString>
int main(int argc,char* argv[])
{
//局部變量
int age = 10;
QString name = "張三";
//創建並初始化
Student* student = (Student*)malloc(sizeof(Student) + name.length());
student->Age = age;
student->Length = name.length();
memcpy(student->Info,name.toLocalBit8().data(),name.length());
//打印
qDebug()<<stutent->Age<<student->Info;
//釋放(一次釋放即可)
free(student);
student = NULL;
}