我一直在开发一个程序,以测试一些字符串操作的可能性。基本上应该读取一个字符串列表,并能够找到一个字符的邻居来遍历字符串。这是代码:

    #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”。我正在使用一些我不习惯的主题和技术,并且可能会滥用。任何帮助都会很棒。

最佳答案

std::string neighbors[4];是堆栈分配的。当您出去getNeighbors时,它会松开范围。尝试将其放到其他位置(甚至是全局性,以作为概念证明)。更好的设计应将此作为对您的功能的约束。

void getNeighbors(int string, int member, std::vector<std::string>& neighbors){
      ;
      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
    }

编辑:
#include <iostream>
    #include <string>
    #include <sstream>
    #include <fstream>

    std::string grid[20]={" "};
    std::string neighbors[4]; //<---------------------------

    std::string get(int string, int member){
      return grid[string].substr(member,1);
    }
    std::string* getNeighbors(int string, int member){
      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];
        }
      }
    }

现在,neighbors是全局的(我不喜欢这样,但是可以为POC做这件事)。

10-06 04:10