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;
}
相关推荐
Zwawa14 小时前
屏幕不止一种:OLED、LCD1602字符屏、TFT/IPS图形屏和串口屏怎么用,这与TTY和PTY又有什么关系
c语言·单片机·嵌入式
Fruiticecake14 小时前
C 程序员速通现代 C++(一):lambda、std::function、移动语义与智能指针
c语言·c++
田甲14 小时前
做一款 Type-C 母座读卡器:GL3224 双卡方案实测
c语言·开发语言
·present·19 小时前
CSAPP(lecture 13_02 Linking)
c语言·c++
wuyk5551 天前
Keil工具链-第05讲-启动文件与__main到底做了什么
c语言·stm32·单片机·嵌入式硬件·物联网
Navigator_Z2 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
冻柠檬飞冰走茶2 天前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
Hhy_11072 天前
《C++深度解构06》手撕 string —— 从底层内存管理到深浅拷贝彻底吃透
c语言·开发语言·c++·学习·visual studio
曦樂~2 天前
Cpp面筋
c语言·c++
HUANGZHENXUAN1233 天前
最大子矩阵和:从 O(n⁴) 到 O(n³) 的列压缩 + Kadane
c语言·前端