杜绝“野指针”

杜绝“野指针”

“野指针”不是 NULL 指针,是指向“垃圾”内存的指针。人们一般不会错用 NULL 指针,因为用 if 语句很容易判断。但是“野指针”是很危险的,if 语句对它不起作用。

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 int main(int argc, char** argv) {
 6         //声明二维数组及变量 
 7     int a[2][3],i,j;
 8     
 9     //从键盘上为数组a赋值
10      for (i=0;i<2;i++) 
11          for (j=0;j<3;j++) 
12          {
13             cout<<"a["<<i<<"]["<<j<<"]=";
14             cin>>a[i][j];
15           }
16 
17     //显示数组a
18      for (i=0;i<2;i++) { 
19          for (j=0;j<3;j++) 
20          {
21             cout<<a[i][j]<<"  ";
22          }
23         cout<<endl;
24     }
25 
26     //找出该数组的最大元素及其下标
27     int h,l,Max=a[0][0];
28      for (i=0;i<2;i++) {  
29          for (j=0;j<3;j++) 
30          {
31             if (Max<a[i][j]) {
32                 Max=a[i][j];
33                 h=i;
34                 l=j;
35             }
36          }
37     }
38      cout<<"Max:"<<"a["<<h<<"]["<<l<<"]="<<a[h][l]<<endl;
39     return 0;
40 }
原文地址:https://www.cnblogs.com/borter/p/9406443.html