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;



}
相关推荐
Allen_LVyingbo13 分钟前
医疗AI多智能体资源调度:用Python构建高性能MCU资源池
开发语言·人工智能·python·算法·知识图谱·健康医疗
叁散15 分钟前
实验项目3 温度传感器
人工智能·算法·机器学习
settingsun122515 分钟前
【AI-算法-02】卷积 Convolution
人工智能·算法
Hcoco_me19 分钟前
大模型面试题48:从白话到进阶详解LoRA 中 r 和 alpha 参数
开发语言·人工智能·深度学习·算法·transformer·word2vec
多米Domi01125 分钟前
0x3f 第24天 黑马web (安了半天程序 )hot100普通数组
数据结构·python·算法·leetcode
Swift社区26 分钟前
LeetCode 468 验证 IP 地址
tcp/ip·算法·leetcode
枫叶丹426 分钟前
【Qt开发】Qt系统(四)-> Qt文件
c语言·开发语言·c++·qt
TDengine (老段)1 小时前
TDengine C/C++ 连接器进阶指南
大数据·c语言·c++·人工智能·物联网·时序数据库·tdengine
黎雁·泠崖2 小时前
栈与队列实战通关:3道经典OJ题深度解析
c语言·数据结构·leetcode
ytttr8739 小时前
隐马尔可夫模型(HMM)MATLAB实现范例
开发语言·算法·matlab