c++ Segmentation fault when trying to reverse print an array

隐身守侯 提交于 2021-02-04 21:01:31

问题


I have a array consisting of chars like [1,2,3,4,5,.,..] and I have a loop that looks like

  for (size_t i = 0; i < size; ++i)
    os << data[i]; // os is std::ostream&

This loop prints the array in the correct order without any errors. But when I use this loop to print it backwards

  for (size_t i = (size - 1); i >= 0; --i)
    os << data[i];

I get a segmentation fault error. Any reason why this can happen?


回答1:


The condition i >= 0 is always true (because size_t is an unsigned type). You've written an infinite loop.

Doesn't your compiler warn you about that? I know g++ -Wextra does here.

What you can do instead is this:

for (size_t i = size; i--; ) {
    os << data[i];
}

This uses post-decrement to be able to check the old value of i, which allows the loop to stop just after i = 0 (at which point i has wrapped around to SIZE_MAX).




回答2:


size_t is unsigned int so it always remain positive, so your loop is an infinite loop




回答3:


You can use a C++ for-in loop to avoid the problem. Example:

#include <iostream>
#include <vector>
#include <boost/range/adaptor/reversed.hpp>

using std::vector;
using std::cout;
using boost::adaptors::reverse;

int main()
{
  auto v = vector<char>{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X' };

  char const* sep = "";
  for (auto c : v)
  {
    cout << sep << c;
    sep = " ";
  }
  cout << "\n";

  sep = "";
  for (auto c : reverse(v))
  {
    cout << sep << c;
    sep = " ";
  }
  cout << "\n";
}


来源:https://stackoverflow.com/questions/49835274/c-segmentation-fault-when-trying-to-reverse-print-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!