闡述 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<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("Enter the number of elements : "); 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 :
"); for(i=0;i<numofe;i++){ scanf("%d",p+i); sum=sum+*(p+i); } printf("
The sum of elements is %d",sum); free(p);//Erase first 2 memory locations// printf("
Displaying the cleared out memory location :
"); for(i=0;i<numofe;i++){ printf("%d
",p[i]);//Garbage values will be displayed// } }
輸出
Enter the number of elements : 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
廣告