Latest web development tutorials

Cライブラリ関数 - のmalloc()

C標準ライブラリ -  <stdlib.h>に含ま C標準ライブラリ- <stdlib.h>に含ま

説明

Cライブラリ関数のvoid * malloc関数(size_tのサイズ)が必要なメモリ領域を割り当て、そのポインタを返します。

声明

ここで、()文のmalloc関数です。

void *malloc(size_t 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

C標準ライブラリ -  <stdlib.h>に含ま C標準ライブラリ- <stdlib.h>に含ま