【发布时间】:2014-02-01 19:38:42
【问题描述】:
我一直在开发一个程序来测试一些字符串操作的可能性。它基本上应该读取字符串列表并能够找到字符的邻居以通过字符串作为电路。代码如下:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
std::string grid[20]={" "};
std::string get(int string, int member){
return grid[string].substr(member,1);
}
std::string* getNeighbors(int string, int member){
std::string neighbors[4];
neighbors[0]=grid[string-1].substr(member,1);//up
neighbors[1]=grid[string+1].substr(member,1);//down
neighbors[2]=grid[string].substr(member-1,1);//left
neighbors[3]=grid[string].substr(member+1,1);//right
std::string* p=neighbors;
return p;//Returns up,down,left,right.
}
int main(int argc, char** argv){
grid[1]="@----^---0";
grid[2]="abcdefghi0";
grid[3]="jklmnopqr0";//TODO Change to read of txt*/
std::string* neighbors;
for(int i=0;grid[1].length()>i;i++){
neighbors=getNeighbors(2,1);
if(neighbors[3]=="-" | neighbors[3]=="^"){
std::string r=get(1,i);
(r!="0") ? std::cout<<r:0;//Dangerous. TODO Unknown symbol handling
std::cout<<neighbors[3];
}
}
}
编译良好,但运行时错误“Segmentation fault: 11”。我正在使用一些我不习惯并且可能滥用的主题和技术。任何帮助都会很棒。
【问题讨论】:
-
在什么编译器下失败了?使用 g++4.8(经过小修复 - 它没有编译!),它可以工作 coliru.stacked-crooked.com/a/bbc1a7134ee38989,但没有输出。
-
是的,我应该提到这一点。我在一个带有 10.9 Mavericks 和 Apple LLVM 版本 5.0 (clang-500.2.79) 的 Mac 上。我可以通过删除 getNeighbors() 的每个调用和引用来停止运行时错误,但这就是程序的重点并控制输出。
标签: c++ crash segmentation-fault runtime-error