C 庫函數– malloc()
描述
C庫函數void *malloc(size_t size)分配所需的內存空間,並返回一個指向它的指針。
聲明
下面是malloc() 函數的聲明。
void *malloc(size_t size)
參數
- size --內存塊的大小,以字節為單位。
返回值
該函數返回一個指針,指向已分配大小的內存。 如果請求失敗,則返回NULL。
實例
下面的實例演示了malloc() 函數的用法。
#include <stdio.h> #include <stdlib.h> int main() { char *str; /* 最初的内存分配 */ str = (char *) malloc(15); strcpy(str, "w3cschool"); printf("String = %s, Address = %u\n", str, str); /* 重新分配内存 */ str = (char *) realloc(str, 25); strcat(str, ".cc"); printf("String = %s, Address = %u\n", str, str); free(str); return(0); }
讓我們編譯並運行上面的程序,這將產生以下結果:
String = w3cschool, Address = 355090448 String = w3cschool.cc, Address = 355090448