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;
}
相关推荐
Discipline~Hai11 小时前
ARM01-ARM体系架构
linux·c语言·arm开发·架构
cjr_xyi13 小时前
AT1202Contest_c binarydigit 题解
c语言·c++·算法
Navigator_Z14 小时前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
无相求码14 小时前
const vs #define:C语言常量定义的差异
c语言·算法
Android洋芋15 小时前
AI辅助C盘清理
c语言·开发语言·人工智能·ai辅助c盘清理
ScilogyHunter15 小时前
GCC/Clang 原始字符串详解
c语言·原始字符串
麻瓜老宋17 小时前
AI开发C语言应用按步走,表达式计算器calc的第四步,交互式 REPL 模式
c语言·开发语言·atomcode
十月的皮皮17 小时前
stm20260719-STM32F103RCT6_HAL库_三人抢答器
c语言·stm32·单片机·嵌入式硬件·stm32cubemx·hal库
特立独行的猫a18 小时前
Python的C/C++三方库移植到鸿蒙PC实战踩坑记
c语言·c++·python·harmonyos·三方库移植·鸿蒙pc
wuyk55518 小时前
53.嵌入式开发中栈溢出的深度解析:从HardFault到解决方案
c语言·stm32·单片机