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;
}
相关推荐
[J] 一坚13 小时前
华为OD、微软、Google、神州数码、腾讯、中兴、网易有道C/C++字符串、数组、链表、树等笔试真题精粹
c语言·数据结构·c++·算法·链表
不会编程的小寒13 小时前
C and C++
java·c语言·c++
不想写笔记14 小时前
C语言 操作符(下)
c语言·笔记
誰能久伴不乏15 小时前
为什么 TCP 服务端重启会出现 “Address already in use”问题解析
linux·服务器·c语言·网络·c++·tcp/ip
VekiSon15 小时前
gdb工具介绍
linux·c语言
黎雁·泠崖15 小时前
VS2022调试通关秘籍:变量跟踪+内存分析+bug定位
c语言·bug
Bigan(安)16 小时前
【奶茶Beta专项】【LVGL9.4源码分析】03-显示框架-display
linux·c语言·mcu·arm·unix
Zsy_05100317 小时前
【数据结构】堆简单介绍、C语言实现堆和堆排序
c语言·数据结构·算法
SongYuLong的博客17 小时前
开源 C 标准库(C Library)
c语言·开发语言·开源
坚持编程的菜鸟17 小时前
模拟实现qsort库函数排序整型和结构体
c语言