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 小时前
AI开发C语言应用按步走,表达式计算器calc的第一步,中缀表达式词法分析
c语言·开发语言·atomcode
一个初入编程的小白8 小时前
C语言:函数栈帧与销毁
c语言·开发语言
ComputerInBook11 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
bu_shuo12 小时前
c与cpp中的argc和argv
c语言·c++·算法
Aurorar0rua12 小时前
CS50 x 2024 Notes Algorithms - 02
c语言·开发语言·学习方法
足球中国13 小时前
nuget把缓存搬离C盘
c语言·windows·缓存
Darkwanderor14 小时前
动、静态库相关内容的详细介绍
linux·c语言·开发语言·c++
胡楚昊15 小时前
洛谷C语言学习小记
c语言·学习·算法
牧以南歌〆18 小时前
数据结构<三>单循环链表
c语言·数据结构·算法·链表
麻瓜老宋19 小时前
AI开发C语言应用按步走,我的基础开发环境
c语言·开发语言