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++ 尝试反向打印数组时出现分段错误
				
        
 
            
        基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				