您的位置:首页 > 编程语言 > C语言/C++

C语言柔性数组

2016-05-19 15:56 363 查看

C语言柔性数组

什么是柔性数组(Fiexibel Array)

在C99中的定义如下

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member.

在至少两个成员的结构体中,最后一个成员可能有不完整类型的数组类型,则该成员称为柔性数组。

struct s
{
int id;
char str[];
}

...

//分配内存
s *pTest = (s*)malloc(sizeof(s) + 100 * sizeof(char));

...

//释放
free(pTest);


s有一个成员str,长度不固定,因此为柔性数组。str长度为0,不占用s的空间,这里str是一个容量为100的char型数组。在使用str时,pTest->str
就可以访问。在使用完后,使用free就可释放。

举例

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct _student
{
int id;
char str[];
}student;

int main()
{
char name[] = "Charlyhash";
student* st = (student*)malloc(sizeof(student) + sizeof(name));
st->id = 1000;
strcpy_s(st->str, sizeof(name),name);

char *p = st->str;
printf("name: %s\n", p);
printf("%ld %ld\n", sizeof(*st), sizeof(int));

return 0;
}
/*
输出:
name: Charlyhash
4 4
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: