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;
}
相关推荐
小莞尔7 小时前
【51单片机】【protues仿真】基于51单片机超声波测距仪系统
c语言·单片机·嵌入式硬件·物联网·51单片机
学逆向的7 小时前
C 宏函数
c语言·开发语言·网络安全
Code_Solitude7 小时前
C语言:指针题型总结
c语言·开发语言
wyhwust7 小时前
程序设计基础-No5课件知识点
c语言
FLJwu8 小时前
运动相机采购选型避坑实战|第二篇
c语言·开发语言·数码相机·运动相机·oem 量产
lhbweilai8 小时前
分析FreeRTOS内核对象API的源码实现(六)
c语言·stm32·单片机
Brilliantwxx9 小时前
【STM32】RTC 完结篇:日期操作、闹钟中断与附录(时间戳 / 闹钟 / NTP)
服务器·c语言·stm32·单片机·嵌入式硬件·实时音视频
学逆向的10 小时前
C 悬空指针
c语言·开发语言·网络安全
·present·1 天前
CSAPP(lecture 4_01)
c语言·c++
本地化文档1 天前
llvm-libc-docs-l10n
c语言·github·gitcode·sphinx·llvm·crowdin