C語言中的malloc函式是什麼意思?
malloc()函式代表記憶體分配,它動態分配記憶體塊。
它為指定大小保留記憶體空間並返回一個空指標,指向該記憶體位置。
malloc()函式附帶垃圾值。返回的指標的型別為void。
malloc()函式的語法如下−
ptr = (castType*) malloc(size);
示例
以下示例顯示了malloc()函式的用法。
#include<stdio.h> #include<string.h> #include<stdlib.h> int main(){ char *MemoryAlloc; /* memory allocated dynamically */ MemoryAlloc = malloc( 15 * sizeof(char) ); if(MemoryAlloc== NULL ){ printf("Couldn't able to allocate requested memory
"); }else{ strcpy( MemoryAlloc,"TutorialsPoint"); } printf("Dynamically allocated memory content : %s
", MemoryAlloc); free(MemoryAlloc); }
輸出
當執行上述程式時,它產生以下結果−
Dynamically allocated memory content: TutorialsPoint
廣告