家庭工作:将一个文件读取到指向指针char(char**)的指针中



我讨厌把家庭作业放在stackoverflow上。提前道歉。

我必须编写一个符合以下声明的函数

char ** read_maze(char *filename, int *rows, int *cols )

到目前为止,我写的功能是

char ** read_maze(char *filename, int *rows, int *cols )
{
  ifstream maze(filename);
  maze >> *rows >> *cols;
  char * contents[] = new char * [*rows * *cols];
  for (int r = 0; r < *rows; r++) {
    for (int c = 0; c < *cols; c++) {
      if (!maze.eof())
        maze >> contents[r][c];
    }
  }
  return contents;
}

我遇到的问题是访问/写入字符数组contents会导致分段错误。我尝试过各种不同的访问器,但似乎无法阻止segfault的发生。

我试过在谷歌上搜索如何在c++中访问点指针字符,但我找不到任何实质性的东西。

我尝试过的东西:*contents[r*c]、(contents+rc)、*((contents[r])+c)和许多其他东西。

如何将文件读取到char **

感谢

我认为您需要的是:

std::ifstream maze(filename);
std::size_t rowCount, colCount;
maze >> rowCount >> colCount;
std::vector<std::vector<char>> content(rowCount, std::vector<char>(colCount));
for (auto &columns : content) {
    for (auto& c : columns) {
        maze >> c;
    }
}

如果你真的想使用new []:

char** read_maze(const char* filename, int& rowCount, int& colCount)
{
    std::ifstream maze(filename);
    maze >> rowCount>> colCount;
    char** contents = new char* [rowCount];
    for (int r = 0; r != rowCount; ++r) {
        contents[r] = new char[colCount];
        for (int c = 0; c != colCount; ++c) {
            if (!maze.eof()) {
                maze >> contents[r][c];
            }
        }
    }
    return contents;
}

但你必须用delete[]:自己销毁你的内容

void delete_maze(char** contents, int rowCount)
{
    for (int r = 0; r != rowCount; ++r) {
        delete [] contents[r];
    }
    delete [] contents;
}

这一行有一个指向字符指针的指针。

  char **contents = new char * [*rows * *cols];

现在你有很多字符指针,你必须分配内存。你可以这样做:

for (int r = 0; r < *rows; r++) {
    for (int c = 0; c < *cols; c++) {
           contents[r][c] = new char[SIZE_OF_STRING];
    }
}

或者,您可以使用std::string来避免C样式的字符*指针。

最新更新