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;
}
相关推荐
小莞尔3 天前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔3 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing102329293 天前
Day03_刷题niuke20250915
c语言
第七序章3 天前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
l1t3 天前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb
l1t3 天前
利用美团龙猫用libxml2编写XML转CSV文件C程序
xml·c语言·libxml2·解析器
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长3 天前
C语言---循环结构
c语言·开发语言·算法
程序猿编码3 天前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备
mark-puls3 天前
C语言打印爱心
c语言·开发语言·算法