C语言柔性数组

在C语言中,结构体定义数组指定长度0,sizeof时候不计入占用,实际分配时候占用为准!

也许你从来没有听说过柔性数组的概念,但其确实存在。C99规定:结构中的最后一个元素允许是未知大小的数组,这就叫做"柔性数组"成员。

test_struct_array.c

c 复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct sa{
        int a;
        char ca[0];//或者char ca[];
};
struct sa_other{
        int a;
        char ca[100];
};
int main(void)
{
        struct sa *sa_ = (struct sa *)malloc(sizeof(struct sa) + 100);
        struct sa_other sa_other_;
        memset(sa_->ca,'\0',100);
        strcpy(sa_->ca, "This is www.spacefly.cn.");
        printf("%zd\n",sizeof(*sa_));
        printf("%s\n",sa_->ca);
        
        printf("%zd\n",sizeof(sa_other_));
        return 0;
}
相关推荐
hefaxiang7 小时前
C语言常见概念(下)
c语言·开发语言
potato_may7 小时前
链式二叉树 —— 用指针构建的树形世界
c语言·数据结构·算法·链表·二叉树
Bona Sun8 小时前
单片机手搓掌上游戏机(二十)—pico运行doom之编译环境
c语言·c++·单片机·游戏机
我真不会起名字啊9 小时前
C、C++中的sprintf和stringstream的使用
java·c语言·c++
剪一朵云爱着11 小时前
PAT 1164 Good in C
c语言·开发语言
Molesidy12 小时前
【C】简易的环形缓冲区代码示例
c语言·开发语言
阿白的白日梦13 小时前
Windows下c/c++编译器MinGW-w64下载和安装
c语言·后端
水饺编程15 小时前
第3章,[标签 Win32] :WM_CREATE 消息的产生
c语言·c++·windows·visual studio
会员果汁15 小时前
双向链式队列-C语言
c语言·数据结构
C语言不精15 小时前
c语言-优雅的多级菜单设计与实现
c语言·开发语言·算法