0
点赞
收藏
分享

微信扫一扫

JAVA 架构师面试 100套含答案:JVM+spring+ 分布式 + 并发编程》...

洛茄 2024-12-05 阅读 10

在C语言中,结构体定义数组指定长度0,sizeof时候不计入占用,实际分配时候占用为准!
也许你从来没有听说过柔性数组的概念,但其确实存在。C99规定:结构中的最后一个元素允许是未知大小的数组,这就叫做“柔性数组”成员。

test_struct_array.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;
}

在这里插入图片描述

举报

相关推荐

0 条评论