c++ Segmentation fault when trying to reverse print an array(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).
这篇关于c++ 尝试反向打印数组时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++ 尝试反向打印数组时出现分段错误
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
