编写一个C程序以使用动态内存分配功能来显示和添加元素。
在C语言中,库函数malloc在运行时以字节为单位分配一个内存块。它返回一个空指针,该指针指向已分配内存的基地址,并且使该内存未初始化。
void *malloc (size in bytes)
例如,
int * ptr;
ptr =(int *)malloc(1000);
int * ptr;
ptr =(int *)malloc(n * sizeof(int));
注–如果内存不是空闲的,则返回NULL。
#include<stdio.h>
#include<stdlib.h>
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<numofe;i++){
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("\nThe sum of elements is %d",sum);
free(p);//Erase first 2 memory locations//
printf("\nDisplaying the cleared out memory location : \n");
for(i=0;i<numofe;i++){
printf("%d\n",p[i]);//Garbage values will be displayed//
}
}输出结果输入元素数: 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