#include<stdio.h>
#include<stdlib.h>
//使用malloc函数动态创建一个数组
int main(){
/*
malloc接收一个整型参数
malloc(20)代表申请20个字节的内存空间
返回申请内存空间的首地址
*/
/*申请一个4*3字节的内存,返回申请内存的首地址
但是内存有了,还要说明用什么数据类型来解析
这段内存。
(char *)malloc(20);
(int *)malloc(20);
(double *)malloc(16);
...
*/
//使用malloc函数创建一个动态数组
int i;
int temp;
printf("请输入数组的长度:");
scanf("%d",&i);
int * p = (int *)malloc(sizeof(int)*i);
//给数组赋值
for(temp=0;temp<i;temp++){
printf("p[%d]=",temp);
scanf("%d",&p[temp]);
}
//输出数组
for(temp=0;temp<i;temp++){
printf("%d,",p[temp]);
}
free(p);
return 0;
}
使用malloc函数创建动态数组
最新推荐文章于 2024-02-05 12:08:44 发布