ポインタ配列


#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)

配列のデータ数に依存しないプログラム

一般にデータ数は場合によって異なります。
そこで配列のデータの終わりに-999という値を置き
これをデータの終わりの印として扱えば
配列のデータに依存しないプログラムを作れます。


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

 while ( a[i] != -999 ) {
  sum += a[i];
  i++;
 }
 printf( "合計:%d\n", sum );
}

C > 配列 | comments (0) | trackbacks (0)