#include <stdio.h>
int main( void )
{
int data1[10] = { 10, 15, 22, 45, 9, 66, 71, 4, 37, 82 };
int data2[10], i, cnt;
int *p1, *p2;
cnt = 0;
p1 = data1; /* 配列data1のアドレスをp1に設定 */
p2 = data2; /* 配列data2のアドレスをp2に設定 */
for ( i = 0; i < 10; i++ ) {
if ( ( ( *p1 )%2 ) == 1 ) { /* p1の指す内容が奇数なら */
*p2 = *p1; /* p2の指す中身に代入 */
printf( "%d\n", *p2 );
p2++; /* ポインタp2の更新 */
cnt++;
}
p1++; /* ポインタp1の更新 */
}
printf( "格納個数 = %d\n", cnt );
return 0;
}
#include <stdio.h>
int main( void )
{
int a[101], i, *p;
p = a; /* ポインタpに配列aのアドレス設定 */
*p = 0; /* 先頭に0代入 */
printf( "%d\t", *p );
for ( i = 1; i < 101; i++ ) {
p++; /* ポインタpの更新 */
*p = *( p-1 )+i; /* 一つ前の値にiを加えて代入 */
printf( "%d\t", *p );
}
printf( "\n" );
return 0;
}
この演習は、配列101個すべてに、0から添字までの合計値を格納する問題です。
二重ループを使ってもいいのですが、解答例では図のように、
*pに一つ前の要素の*(p-1)に添字を加えたものを格納しています。
先頭要素は*(p-1)を加えるわけにはいかないので、先に0を代入し、
それからp++してから処理を行っています。
▼戻る▼
「初心者のためのポイント学習C言語」 Copyright(c) 2000-2004 TOMOJI All Rights Reserved