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