解释C编程中的malloc函数
问题
编写一个C程序以使用动态内存分配功能来显示和添加元素。
解决方案
在C语言中,库函数malloc在运行时以字节为单位分配一个内存块。它返回一个空指针,该指针指向已分配内存的基地址,并且使该内存未初始化。
语法
void *malloc (size in bytes)
例如,
int*ptr;
ptr=(int*)malloc(1000);
int*ptr;
ptr=(int*)malloc(n*sizeof(int));
注–如果内存不是空闲的,则返回NULL。
示例
#include#include void main(){ //Declaring variables and pointers,sum// int numofe,i,sum=0; int *p; //Reading number of elements from user// printf("输入元素数: "); scanf("%d",&numofe); //Calling malloc() function// p=(int *)malloc(numofe*sizeof(int)); /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Printing elements// printf("Enter the elements : \n"); for(i=0;i 输出结果 输入元素数: 5 Enter the elements : 23 45 65 12 23 The sum of elements is 168 Displaying the cleared out memory location : 10753152 0 10748240 0 23
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短