學習C++,寫了一個簡單的陣列回圈賦值程式。用的DEV C++ 5.11.
出了個奇怪的問題,程式中注釋的那一行會導致回圈不能跳出。想了很久沒弄明白。
#include <iostream>
using namespace std;
int main(){
unsigned char c=0,d=0;
unsigned int e[255][255];
do{
if(!((int) c^255)){
break;
}
c++;
d=0;
do{
cout << (int) c << "," << (int) d << endl;
e[c][d]=c+d; //沒有這一行就可以正常跳出回圈。
cout<< "e[" << (int) c << "]" << "[" << (int) d << "]" << ":" << e[c][d] <<endl;
if(!((int) d^255)){
break;
}
d++;
}while(1);
}while(1);
return 0;
}
uj5u.com熱心網友回復:
供參考:#include <iostream>
using namespace std;
int main()
{
unsigned char c=0,d=0;
unsigned int e[255][255];
do{
if(!((int) c^254)){ //陣列下標是0-254,255越界了
break;
}
c++;
d=0;
do{
cout << (int) c << "," << (int) d << endl;
e[c][d]=c+d; //沒有這一行就可以正常跳出回圈。
cout<< "e[" << (int) c << "]" << "[" << (int) d << "]" << ":" << e[c][d] <<endl;
if(!((int) d^254)){ //陣列下標是0-254,255越界了
break;
}
d++;
}while(1);
}while(1);
system("pause");
return 0;
}
//輸出:
//1,0
//e[1][0]:1
//1,1
//e[1][1]:2
//1,2
//e[1][2]:3
//......
//......
//e[1][253]:254
//1,254
//e[1][254]:255
//2,0
//e[2][0]:2
//2,1
//e[2][1]:3
//2,2
//e[2][2]:4
//2,3
//e[2][3]:5
//......
//......
//254,250
//e[254][250]:504
//254,251
//e[254][251]:505
//254,252
//e[254][252]:506
//254,253
//e[254][253]:507
//254,254
//e[254][254]:508
//請按任意鍵繼續. . .
uj5u.com熱心網友回復:
從0開始,還得調整下陳述句順序,還得等它點時間:#include <iostream>
using namespace std;
int main()
{
unsigned char c=0,d=0;
unsigned int e[255][255];
do{
d=0;
do{
cout << (int) c << "," << (int) d << endl;
e[c][d]=c+d;
cout<< "e[" << (int) c << "]" << "[" << (int) d << "]" << ":" << e[c][d] <<endl;
if(!((int) d^254)){ //陣列下標是0-254,255越界了
break;
}
d++;
}while(1);
if(!((int) c^254)){ //陣列下標是0-254,255越界了
break;
}
c++;
}while(1);
system("pause");
return 0;
}
//輸出:
//0,0
//e[0][0]:0
//0,1
//e[0][1]:1
//0,2
//e[0][2]:2
//0,3
//e[0][3]:3
//0,4
//e[0][4]:4
//......
//......
//1,0
//e[1][0]:1
//1,1
//e[1][1]:2
//1,2
//e[1][2]:3
//......
//......
//e[1][253]:254
//1,254
//e[1][254]:255
//2,0
//e[2][0]:2
//2,1
//e[2][1]:3
//2,2
//e[2][2]:4
//2,3
//e[2][3]:5
//......
//......
//254,250
//e[254][250]:504
//254,251
//e[254][251]:505
//254,252
//e[254][252]:506
//254,253
//e[254][253]:507
//254,254
//e[254][254]:508
//請按任意鍵繼續. . .
uj5u.com熱心網友回復:

從斷點除錯中可以看出,變數c,d就放在陣列e后面,而代碼中陣列操作越界,就是加了注釋的那一行代碼做了越界操作(陣列的合法下標是0-254),覆寫了c,d的值,導致回圈不會終止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/252258.html
標籤:新手樂園
