malloc で領域を確保

昔ながらの malloc で領域を確保して free で開放します。
お勧めの方法は new でメモリ領域の割り当て を参照して下さい。

前田稔(Maeda Minoru)の超初心者のプログラム入門

プログラムの説明

  1. 昔ながらの malloc で領域を確保して、free で開放してみましょう。
    malloc(sizeof(struct person)) で構造体 person の領域を確保します。
    確保した領域に名前と年齢を格納して表示してみました。
    malloc で確保した領域は free で開放して下さい。
    /*★ Malloc で領域を確保    前田 稔 ★*/
    #include <stdio.h>
    #include <malloc.h>
    
    struct person
    {   char    *name;
        int     year;
    };
    
    int main(void)
    {
        person  *ptr = NULL;
        ptr = (struct person *)malloc(sizeof(struct person));
        ptr->name = "ann";
        ptr->year = 20;
        printf("name=%s  year=%d\n", ptr->name,ptr->year);
        free(ptr);
        return 0;
    }
    
  2. int の領域を確保するときは、次のようにコーディングします。
        int *p;
        p = (int *)malloc(sizeof(int));
        
  3. malloc(GlobalAlloc)の詳しい説明は、次のページを参照して下さい。
    GlobalAlloc でメモリ領域の割り当て
    LocalAlloc でメモリ領域の割り当て

【メモ】

最近では関数で領域を確保する方法は使われなくなり、new, delete が使われるようになりました。
理由は簡単でコンストラクタが呼び出せないからです。
実は C++ では、int型のような基本データ型にもコンストラクタがあります。
C# では int型 に ToString() などのメソッドも用意されています。

超初心者のプログラム入門(C/C++)