●型キャスト

 「型キャスト演算子」を使うと,ある型のデータを強制的に別のデータ型に変換することが出来る。

 

 (変換後の型)元のデータ 

 

例:

  
int x;
double * dp = (double*)&x;  /* int*型ポインタを強制的にdouble*型ポインタに変換している。通常はこのような型変換は危険。 */
  
●変数やデータ型のサイズ(バイト数)の取得 〜 sizeof 演算子

 

 sizeof( データ型名 ) 
 sizeof( 変数名 ) または sizeof 変数名


 ※sizeof演算子は size_t型 というサイズの大きい符号なし整数(0以上の整数) でバイト数を返す。
 ※size_t 型は,たいてい unsigned long と同じ型として typedef などを使って定義されている。(例:typedef unsigned long size_t;)
  そのため,printf関数ではunsigned long型を表示するための"%lu"変換指定で,size_t 型の値を表示できる。
 


●メモリの動的割り当て(dynamic memory allocation)

 メモリを必要に応じて割り当てるために,malloc()関数が利用できる。また,割り当てたメモリはfree()関数で解放できる。


セルを動的に割り当ててリストを構築する例

#include <stdio.h>
#include <stdlib.h>
 
struct Cell {
    int data;
    struct Cell * next;
};
 
typedef struct Cell Cell;
 
int main() {
    int i, n = 0;
    Cell * p = NULL;
    Cell * pre = NULL; // ひとつ前に生成したセルのアドレス(セル生成時に利用)
    Cell start;        // 便宜的に用意したスタートセル
 
    start.data = 0; start.next = NULL;
    printf( "num of cell : " ); scanf( "%d", &n );
 
    pre = &start;
    for( i = 0; i < n; i++ ) {
        p = (Cell*)malloc( sizeof(Cell) ); // Cell型変数用のメモリ領域を取得
        if( p == NULL ) break;
        p->data = i;
        p->next = NULL;
        pre->next = p;
        pre = p;
    }
 
    p = start.next;
    while ( p != NULL ) {
        printf( "%d\n", p->data );
        p = p->next;
    }
    
    /* 動的に割り当てたCell型変数をすべて解放する。 */
    p = start.next;
    while ( p != NULL ) {
        Cell * tp = p;
        p = p->next;
        free(tp);
    }
    
    getchar();getchar();
    return 0;
}