例を使用した C ライブラリの malloc() 関数
C の malloc とは?
malloc() 関数は、メモリ割り当てを表します。これは、メモリのブロックを動的に割り当てるために使用される関数です。指定されたサイズのメモリ空間を予約し、メモリ位置を指す null ポインタを返します。通常、返されるポインタは void 型です。これは、malloc 関数を任意のポインターに割り当てることができることを意味します。
構文
ptr = (cast_type *) malloc (byte_size);
ここで、
- ptr は cast_type のポインタです。
- malloc 関数は、byte_size の割り当てられたメモリへのポインタを返します。
Example: ptr = (int *) malloc (50)
このステートメントが正常に実行されると、50 バイトのメモリ空間が確保されます。予約済みスペースの最初のバイトのアドレスは、int 型のポインター ptr に割り当てられます。
malloc 実装の別の例を考えてみましょう:
#include <stdlib.h> int main(){ int *ptr; ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */ if (ptr != NULL) { *(ptr + 5) = 480; /* assign 480 to sixth integer */ printf("Value of the 6th integer is %d",*(ptr + 5)); } }
出力:
Value of the 6th integer is 480
Malloc 関数は、文字データ型だけでなく、構造体などの複雑なデータ型でも使用できます。
C言語