汎用ポインタ

void *変数名


#include <stdio.h>

typedef struct tagTest {
 char c;
 int i;
} _TEST;

void Disp( void *t )
{
 printf( "%d\n", sizeof( *(_TEST*)t ) );
}

void main()
{
 _TEST test;
 Disp( &test );
}


汎用ポインタは任意のポインタを代入する事が可能であり、
同様に型キャストによって型を復元させる事ができます。


#include <stdio.h>

void Disp( void *t )
{
 char *pstr = (char*)t;
 puts( pstr );
 putchar( (int)*pstr );

 int *pd = (int*)t;
 putchar( *pd );
}

void main()
{
 char *str = "abcdefg";
 Disp( str );
}


あらゆる型のポインタをキャストできます。
C > ポインタ | comments (0) | trackbacks (0)

ポインタ配列


#include <stdio.h>
void main()
{
 char *str[] = { "Candy", "Nancy", "Eluza", "Ann" };
 int i, j;

 // 1行ずつ出力
 for ( i=0; i<4; i++ )
  printf( "%s\n", str[ i ] );

 // 1文字ずつ出力
 for ( i=0; i<4; i++ ) {
  j = 0;
  while ( str[ i ][ j ] != '\0' ) {
   putchar( str[ i ][ j ] );
   j++;
  }
  putchar( '\n' );
 }
}

C > ポインタ | comments (0) | trackbacks (0)

ポインタと2次元配列


#include <stdio.h>
void main()
{
 int a[][4] = { { 1, 2, 3, 0 }
        , { 4, 5, 6, 0 }
        , { 7, 8, 9, -999 } };

 int *pa = a[0];

 while ( *pa != -999 ) {
  printf( "%d ", *pa );
  pa++;
 }
}


a[0]は2次元配列の先頭アドレスを示すポインタ定数と考えらる。
C > ポインタ | comments (0) | trackbacks (0)

アドレス計算


#include <stdio.h>
void main()
{
 char* str = "hello";
 int i;

 for ( i=0; i<5; i++ ) {
  putchar( *( str + i ) );
  putchar( str[ i ] ); // 配列としての実体はない
 }
}

C > ポインタ | comments (0) | trackbacks (0)