【发布时间】:2021-06-25 12:10:18
【问题描述】:
为什么while(p != p+sz)是下面代码中的错误:-
#include<iostream>
using std::cout;
using std::endl;
int main(){
int arr[] = {1,2,3,4,5};
int sz= (sizeof(arr)/sizeof(arr[0]));
int *p = arr, *l = &arr[sz];
while(p != p+sz){
*p = 0;
p++;
}
for(auto i: arr){
cout<<i<<endl;
}
return 0;
}
但是,如果我将 while 条件更改为 while(p != l),它会起作用,但为什么我无法使用关系运算符( while(p < p+sz) 或向指针添加整数值(while(p != p+sz)?
输出为:Segmentation fault (core dumped)
【问题讨论】:
-
当
sz不为0 时,表达式p != p+sz何时会为假?尝试为p和sz提供一些会产生错误结果的值。 -
你在问为什么 x 不能等于 x+y 对于非零 y?
-
在
while循环条件中,尝试p != p+sz,而不是p != arr+sz。