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 */
相关文章推荐
- c语言,读取一个内容长度未知的文本文件。
- c++指针的指针和指针的引用
- C++ limits头文件
- C语言:标识符
- C++中的指针与引用详细解读
- C语言中数据类型所占字节数总结
- Eclipse支持 C++ 11
- C语言运算符优先级和口诀
- C语言:变量定义
- 【C++专题】static_cast, dynamic_cast, const_cast探讨
- C++中常见类型转换
- 1008. 数组元素循环右移问题 (20)
- 【C++】:关于C++的这些概念你知道吗?
- C++三大函数(The Big Three)
- C++学习笔记(四)
- C++ 栈 与 堆 【GeekBand 第二周】
- C语言中打开文件读取,写入的操作
- 【C++】:C++之函数模板
- C/C++预定义宏
- 由C++的泛型句柄类思考OpenCV的Ptr模板类