接下来两个不同形式动态开辟数组空间
1.柔性数组的使用 优--效率高,内存利用率高
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
typedef struct S
{
int a;
char arr[];//未知大小的柔性数组成员 数组的大小是可以调整的
}s;
int main()
{
//printf("%d\n",sizeof(s));//最后一个数组不占空间
s*ps= (s*)malloc(sizeof(s) + 5 * sizeof(int));//开辟24个字节空间
if (ps == NULL)
{
return 0;//开辟失败则退出
}
else
{
ps->a = 100;
int i = 0;
int a = 100;
for (i = 0; i < 5; i++)
{
ps->arr[i] = i;
}
for (i = 0; i < 5; i++)
{
printf("%d ",ps->arr[i]);
}
//重新开辟44个字节
s*ptr=(s*)realloc(ps, 44);
if (ptr != NULL)
{
ps = ptr;
}
for (i = 5; i < 10; i++)
{
ps->arr[i] = i;
}
for (i = 5; i < 10; i++)
{
printf("%d ",ps->arr[i]);
}
free(ps);
ps = NULL;
}
return 0;
}
2.直接操作数组开辟空间--差(malloc越多内存碎片越多,又比较繁琐)
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
typedef struct S
{
int n;
int* arr;
}s;
int main()
{
s *ps=(s*)malloc(sizeof(s));
ps->arr = malloc(5 * sizeof(int));
if (ps == NULL)
{
return 0;
}
int i = 0;
for (i = 0; i < 5; i++)
{
ps->arr[i] = i;
}
for (i = 0; i < 5; i++)
{
printf("%d ",ps->arr[i]);
}
//调整大小
int*ptr=realloc(ps->arr, 10 * sizeof(int));
if (ptr != NULL)
{
ps->arr = ptr;
}
for (i = 5; i < 10; i++)
{
ps->arr[i] = i;
}
for (i = 5; i < 10; i++)
{
printf("%d ",ps->arr[i]);
}
//释放内存
free(ps->arr);
ps->arr = NULL;
free(ps);
ps = NULL;
return 0;
}
标签:ps,arr,int,++,数组,柔性,sizeof,NULL
From: https://blog.51cto.com/u_16425777/9135004