C
1コード 2//多次元配列でのポインタ利用 3#include <stdio.h> 4 5#define row 3 //行 6#define col 2 //列 7// 56 60 8//54 65 9//12 98 10 int main(int argc, char const *argv[]) { 11//点数入力 12int score[row][col] = {{56, 60}, {54, 65}, {12, 98}}; 13//ポインタ利用で要素表示 14//行ごとに表示 15printf("\n"); 16for (int i = 0; i < row; i++ ){ 17 printf("\n (score + %d)= %p\t\n\n",i, (score + i) ); 18 19//列ごとに表示 20 for (int j = 0; j < col; j ++){ 21 printf("(*(score + %d) + %d) = %p\t\n",i, j, (*(score + i) + j) ); 22 printf("*(*(score + %d) + %d) = %d\t\n",i, j, *(*(score + i) + j) ); 23 } 24 printf("\n"); 25} 26printf("\n"); 27 return 0; 28}
これを実行するとErrorなく次のようになりました。
C
1コード 2 (score + 0)= 0x7ffee0038a30 3 4(*(score + 0) + 0) = 0x7ffee0038a30 5*(*(score + 0) + 0) = 56 6(*(score + 0) + 1) = 0x7ffee0038a34 7*(*(score + 0) + 1) = 60 8 9 10 (score + 1)= 0x7ffee0038a38 11 12(*(score + 1) + 0) = 0x7ffee0038a38 13*(*(score + 1) + 0) = 54 14(*(score + 1) + 1) = 0x7ffee0038a3c 15*(*(score + 1) + 1) = 65 16 17 18 (score + 2)= 0x7ffee0038a40 19 20(*(score + 2) + 0) = 0x7ffee0038a40 21*(*(score + 2) + 0) = 12 22(*(score + 2) + 1) = 0x7ffee0038a44 23*(*(score + 2) + 1) = 98 24
これを見るに、score+0は0行目の一番最初の要素、すなわち0行0列のscore[0][0]のAdressを格納するポインタ変数のように思われます。
score+1についても同様でscore[1][0]のAdressを格納しているポインタ変数のように思われます。
そこで
C
1コード 2 printf("\n *(score + %d)= %d\t\n\n",i, *(score + i) );
を付け加えたところ、
C
1コード 2multi_array.c:17:42: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat] 3 printf("\n *(score + %d)= %d\t\n\n",i, *(score + i) ); 4 ~~ ^~~~~~~~~~~~ 51 warning generated.
のようにErrorが出ました。
そもそも、(score+0)は何を示しているのでしょうか。score+0がscore[0][0]のAdressと一致したのでを先頭につければその要素を示していると考えたのですが...。
まだポインタ変数について理解が浅いので質問がよろしくないかもしれませんがご回答お待ちしています。
回答2件
あなたの回答
tips
プレビュー