【问题标题】:Why relational operator not working in pointers and arrays [closed]为什么关系运算符不能在指针和数组中工作[关闭]
【发布时间】: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 &lt; p+sz) 或向指针添加整数值(while(p != p+sz)?

输出为:Segmentation fault (core dumped)

【问题讨论】:

  • sz 不为0 时,表达式p != p+sz 何时会为假?尝试为psz 提供一些会产生错误结果的值。
  • 你在问为什么 x 不能等于 x+y 对于非零 y?
  • while循环条件中,尝试p != p+sz,而不是p != arr+sz

标签: c++ arrays pointers


【解决方案1】:

您将永远无法达到p + x 本身递增p,它将始终与p 完全是x 步骤。您循环将指针置于其边界之外,然后取消引用它。

您应该使用p 预先计算该值,然后使用它:

// ...
auto limit = p+sz; // Pre-compute the limit
while (p != limit){
    *p = 0;
    p++;
} // ...

【讨论】:

  • 非常感谢,您用更好的解决方案解释得很好。谢谢:)
【解决方案2】:

为什么关系运算符不能处理整数?

更简单的例子,同样的效果:

int main(){
  int sz= 5;
  int p = 0;

  while(p != p+sz){
    p++;
  }
}
   

无论你增加多少p,它永远不会等于p+5

【讨论】:

  • 我明白了,问这样的问题真是太愚蠢了。但我真的太困惑了,谢谢伙计
  • @Shubharthak 提问绝不是愚蠢的。另外,不确定是不是只有我一个人,但我认为回答“哦,这只是一个愚蠢的错误”这样的答案是不礼貌的,只是说......
猜你喜欢
  • 2017-02-12
  • 2012-12-19
  • 2013-06-06
  • 1970-01-01
  • 2019-10-06
  • 2021-10-17
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多