c++ 尝试反向打印数组时出现分段错误
我有一个由 [1,2,3,4,5,.,..] 之类的字符组成的数组,并且我有一个看起来像
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?
推荐答案
条件 i >= 0
始终为真(因为 size_t
是无符号类型).你写了一个无限循环.
The condition i >= 0
is always true (because size_t
is an unsigned type). You've written an infinite loop.
你的编译器不会警告你吗?我知道 g++ -Wextra
在这里.
Doesn't your compiler warn you about that? I know g++ -Wextra
does here.
您可以这样做:
for (size_t i = size; i--; ) {
os << data[i];
}
这使用后减量来检查 i
的旧值,这允许循环在 i = 0
之后停止(此时 >i
已环绕到 SIZE_MAX
).
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
).
相关文章