次のコードがあり、質問では出力を見つけるように求められます。出力 (2) を入力して見つけましたが、その方法/理由を理解するのに苦労しています。ヘルプはありますか?
コードは次のとおりです。
int scores[5];
int *numbers = scores;
for (int i=0; i <=4; i++)
*(numbers+i)=i;
cout << numbers[2] <<endl;
あなたのコードは本質的に
scores[2] = 2;
cout<<scores[2]<<endl;
したがって、答えは..
さらに詳細に:
int scores[5];
int *numbers = scores; //numbers points to the memory location of the array scores
for (int i=0; i <=4; i++) // as mentioned, stray ';'
*(numbers+i)=i; //same as numbers[i] = i which is same as scores[i] = i
cout << numbers[2] <<endl;
for ループによって実行される唯一のステートメントは次のとおりです。
*(numbers+i)=i;
int 要素のインデックスをその位置に格納するには、参照演算子 (*) を使用します。
次に、配列はインデックス 0 から始まるため、2 に相当する 3 番目の数値を出力しています。