タグ

c++とpointerに関するincepのブックマーク (2)

  • ポインタ虎の巻~ポインタの型

    ここでは、変数には、整数型int,文字型char,浮動小数点型doubleなどの型があることに注意してポインタを見て行こう。 これらの変数の型は、その変数の値が必要とするメモリのサイズの情報を持っている。一般的なUNIXでは、int = 4byte, char=1byte, double=8byte が普通であり、変数の型に合わせてその変数がメモリ上で占めるべきサイズが確保されている。サイズを知るためには printf("size of int=%d\n", sizeof(int)); printf("size of char=%d\n", sizeof(char)); printf("size of double=%d\n", sizeof(double)); printf("size of pointer to char=%d\n", sizeof(char *)); printf("

  • メモリリークしない安全なプログラムの書き方

    とりあえず動くプログラムを書く ここでは例として、Fooという構造体の2次元配列を、引数で指定された幅と高さで作る、createFooMatrixという関数を作ってみます。 なお、配列の各要素を、initializeFoo関数で初期化しています。 Foo **createFooMatrix ( int width, int height ) { Foo **ptr = NULL; int w, h; ptr = (Foo **)malloc(height * sizeof(Foo *)); for (h = 0 ; h < height ; h++) { ptr[h] = (Foo *)malloc(width * sizeof(Foo)); for (w = 0 ; w < width ; w++) { initializeFoo(&ptr[h][w]); } } return ptr;

  • 1