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;



}
相关推荐
我想进大厂29 分钟前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂34 分钟前
图论---Bellman-Ford算法
数据结构·c++·算法·图论
AIGC大时代36 分钟前
高效使用DeepSeek对“情境+ 对象 +问题“型课题进行开题!
数据库·人工智能·算法·aigc·智能写作·deepseek
lkbhua莱克瓦241 小时前
用C语言实现——一个中缀表达式的计算器。支持用户输入和动画演示过程。
c语言·开发语言·数据结构·链表·学习方法·交友·计算器
CODE_RabbitV1 小时前
【深度强化学习 DRL 快速实践】近端策略优化 (PPO)
算法
lwewan2 小时前
26考研——存储系统(3)
c语言·笔记·考研
Wendy_robot2 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
程序员-King.2 小时前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
转基因3 小时前
Codeforces Round 1020 (Div. 3)(题解ABCDEF)
数据结构·c++·算法
我想进大厂4 小时前
图论---Kruskal(稀疏图)
数据结构·c++·算法·图论