#include <stdio.h>
#include <string.h>
#include <memory>
// 学生结构体
typedef struct ST_STUDENT
{
int nAge;
char strName[50];
}ST_STUDENT;
// 班级结构体
typedef struct ST_CLASS
{
char strClassName[50];
int nLen;// 存储stStudent的长度(即stStudent的元素个数)
ST_STUDENT stStudent[0];// 定义柔性数组
}ST_CLASS;
int main(int argc, char* argv[])
{
int nLen = 3;
int nSize = sizeof(ST_CLASS) + nLen * sizeof(ST_STUDENT);// 注意这里计算内存的大小方式
ST_CLASS *pstClass = (ST_CLASS*)malloc(nSize);
memset(pstClass, 0, nSize);
strcpy(pstClass->strClassName, "计科一班");
pstClass->nLen = 3;
strcpy(pstClass->stStudent[0].strName, "张三");
pstClass->stStudent[0].nAge = 21;
strcpy(pstClass->stStudent[1].strName, "李四");
pstClass->stStudent[1].nAge = 22;
strcpy(pstClass->stStudent[2].strName, "王五");
pstClass->stStudent[2].nAge = 23;
for (int i = 0 ; i < pstClass->nLen ; ++i)
{
printf("name: %s, age: %d\n", pstClass->stStudent[i].strName, pstClass->stStudent[i].nAge);
}
return 0;
}
柔性数组
最新推荐文章于 2024-06-08 18:52:00 发布