最近在研究C语言相关的东西,遇到了一些问题,主要是关于数组内存分配的问题。我们最常用的数组分配方式就是使用 int array[] ={1,2,3,4}来分配固定长度的数组,但是当需要动态分配数组长度的时候怎么办呢?最近在使用的时候就遇到了,然后自己搜了搜相关的使用方法。
1.先介绍基本数据类型的创建方法
int array;
printf(“请输入数组的长度:”);
scanf("%d",&n);
array=(int)calloc(n,sizeof(int));//calloc()表示分配n*sizeof(int)长度的内存
2.结构体的创建方法
typedef struct str
{
int a;
char b;
}str;
int array;
printf(“请输入数组的长度:”);
scanf("%d",&n);
array=(int)calloc(n,sizeof(str));//这里直接使用sizeof(str)就行了。