當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);
   
   return(0);
}

讓我們編譯並運行上麵的程序,它會產生以下結果——

String = tutorialspoint, Address = 355090448
String = tutorialspoint.com, Address = 355090448

相關用法


注:本文由純淨天空篩選整理自 C library function - malloc()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。