C stdlib malloc() 函式
示例
分配記憶體並讀取其內容
// Allocate memory for a number of items
int numItems = 15;
int *myArray = malloc(numItems * sizeof(int));
// Display the contents of the memory
for(int i = 0; i < numItems; i++) {
printf("%d ", myArray[i]);
}
// Free the memory
free(myArray);
myArray = NULL;
自己動手試一試 »
定義和用法
malloc()
函式用於分配記憶體並返回指向它的指標。與 calloc()
不同,malloc()
分配的記憶體未初始化,因此其中的值是不可預測的。
malloc()
函式定義在 <stdlib.h>
標頭檔案中。
要了解更多關於記憶體分配的資訊,請參閱我們的 C 記憶體管理教程。
語法
malloc(size_t size);
size_t
資料型別是一個非負整數。
引數值
引數 | 描述 |
---|---|
大小 | 指定要分配的記憶體位元組數。 |
技術詳情
返回 | 指向新分配記憶體塊的 void * 指標。 |
---|