指针自加读整型数组的时侯读不出0元素,而且数组大小要比数组中非零元素的个数大,否则会读出随机数
#include<stdio.h>
#include<iostream>
using namespace std;
main()
{
int b[6]={5,8,3,4,0};
int* a=b;
while(*a)
{
cout<<*a<<endl;
a++;
}
return 0;
}
这种的结果是
5
8
3
4
#include<stdio.h>
#include<iostream>
using namespace std;
main()
{
int b[6]={5,8,3,4,1};
int* a=b;
while(*a)
{
cout<<*a<<endl;
a++;
}
return 0;
}
这种的结果是
5
8
3
4
1
#include<stdio.h>
#include<iostream>
using namespace std;
main()
{
int b[5]={5,8,3,4,1};
int* a=b;
while(*a)
{
cout<<*a<<endl;
a++;
}
return 0;
}
这种结果是
5
8
3
4
1
1703808
4332105
1
10228376
10228496
4331872
4331872
3842048
因为你没法保证a[4]的下一个存储单元的值是0,这个内存上是随机的值
因此while(*a)可能导致越界发生,读取到了a[4]数组之后的内存,停不下来,输出了很多别的东西。
while(*a) 是*a这个值是判断的条件。如果*a是非0条件满足,就输出,*a是0就不输出,你把数组的任意一项设置为0,输出结构只有第一个0之前的元素。