o**********a 发帖数: 330 | 1 #include
using namespace std;
int str(const char a[]){
int count=0;
while(a[count]){++count;}
return count;
}
int main(){
char lots[1000];
int nchar=str(lots);
cout<
return 0;
}
为什么nchar=1011 |
p***o 发帖数: 1252 | 2 The program has UNDEFINED behavior. So you can get ANY int as the output.
To see why:
1 Since you didn't initialize lots[1000], reading a[count] for any
0 <= count < 1000 is undefined.
2 Reading a[count] for any count >= 1000 is undefined. You need to
guard against it.
【在 o**********a 的大作中提到】 : #include : using namespace std; : int str(const char a[]){ : int count=0; : while(a[count]){++count;} : return count; : } : int main(){ : char lots[1000]; : int nchar=str(lots);
|
a********n 发帖数: 1287 | 3 1011只是巧合,
可能是任意大于1000的结果。
字符数组不是字符串,不是以NULL结尾的。 |
f*****Q 发帖数: 1912 | 4 为什么不能是小于呢?
【在 a********n 的大作中提到】 : 1011只是巧合, : 可能是任意大于1000的结果。 : 字符数组不是字符串,不是以NULL结尾的。
|
a********n 发帖数: 1287 | 5 你说的对,可能小于1000
【在 f*****Q 的大作中提到】 : 为什么不能是小于呢?
|
e*******c 发帖数: 804 | 6 try the change below.
char lots[1000] = {'\0'};
【在 o**********a 的大作中提到】 : #include : using namespace std; : int str(const char a[]){ : int count=0; : while(a[count]){++count;} : return count; : } : int main(){ : char lots[1000]; : int nchar=str(lots);
|