我有以下代碼,問題讓我找到輸出。我已經找到輸出(2)了,但我無法弄清楚如何/爲什麼。任何幫助?C++代碼輸出說明
下面的代碼:
int scores[5];
int *numbers = scores;
for (int i=0; i <=4; i++)
*(numbers+i)=i;
cout << numbers[2] <<endl;
我有以下代碼,問題讓我找到輸出。我已經找到輸出(2)了,但我無法弄清楚如何/爲什麼。任何幫助?C++代碼輸出說明
下面的代碼:
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;
唯一的語句是由lo執行op是
*(numbers+i)=i;
這將在INT元素的索引存儲在使用順從操作者(*)該位置。
接着要打印出來的第三數量,這相當於2中,由於陣列開始索引爲0
您可以設置一個指針到所述陣列的第一存儲器位置,然後遍歷一系列存儲器地址和寫給他們。應當指出的是,使用指針運算與反引用,
*(pointer + i) = i;
是與使用下標操作符:
pointer[i] = i;