C语言 柔性数组

柔性数组:结构体中最后一个元素是未知大小的数组,数组大小可变

柔性数组特点

①结构体中的柔性数组成员前面必须至少有一个其他成员

②sizeof返回的结构体大小不包括柔性数组的内存

③包含柔性数组成员的结构体要用malloc()函数进行内存分配

使用free函数释放一块内存,不能多次释放同一块内存 ,否则程序会崩溃

柔性数组使用举例(结构体成员内存是连续的)

c 复制代码
#include<stdio.h>
#include<stdlib.h>

struct S{
    int a;
    int arr[0];
};
int main(){
    struct S stu;
    printf("%d\n",sizeof(stu));
    //结果是4 数不包含柔性数组的大小
    
    struct S *temp=(struct S*)malloc(4*sizeof(int));
    for(int i=0;i<3;i++)
    {
        temp->arr[i]=i;
    }
    for(int i=0;i<3;i++)
    {
        printf("%d",temp->arr[i]);
    }
    //利用realloc改变数组大小
    struct S *te=realloc(temp,10*sizeof(int));
    if(te!=NULL)
    {
        temp=te;
    }
    for(int i=3;i<9;i++)
    {
        temp->arr[i]=i;
    }
    for(int i=3;i<9;i++)
    {
        printf("%d",temp->arr[i]);
    }
    free(temp);
    temp=NULL;
return 0;
}

使用指针实现柔性数组的操作举例(结构体成员内存是不连续的)

c 复制代码
#include<stdio.h>
#include<stdlib.h>

struct S{
    int a;
    int *arr;
};
int main(){
    struct S stu;
    struct S *temp=(struct S*)malloc(sizeof(struct S));
    temp->arr=(int *)malloc(3*sizeof(int));
    for(int i=0;i<3;i++)
    {
        temp->arr[i]=i;
    }
    for(int i=0;i<3;i++)
    {
        printf("%d",temp->arr[i]);
    }
    int *te=realloc(temp->arr,10*sizeof(int));
    if(te!=NULL)
    {
        temp->arr=te;
    }
    for(int i=3;i<10;i++)
    {
        temp->arr[i]=i;
    }
    for(int i=3;i<10;i++)
    {
        printf("%d",temp->arr[i]);
    }
    free( temp->arr);
    temp->arr=NULL;
    free(temp);
    temp=NULL;



}
相关推荐
惯导马工18 分钟前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农2 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了2 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo3 小时前
322:零钱兑换(三种方法)
算法
NAGNIP20 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队21 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法