简体   繁体   English

将结构传递给函数以编辑数组导致C ++ seg错误

[英]C++ seg fault as a result of passing struct into function to edit array

Im working on a project to make a word scramble game and currently working on putting the letters in an array of strings. 我正在做一个打单词游戏的项目,目前正在将字母放入一个字符串数组中。 Currently not using any pointers and I worry that that is the cause but I am fairly confused at this point because my assignment requires me to use structs. 当前不使用任何指针,我担心这是原因,但在这一点上我很困惑,因为我的作业要求我使用结构。

Any help would be greatly appreciated, Thanks. 任何帮助将不胜感激,谢谢。

struct definition: 结构定义:

struct puzzle {
int cols;
int rows;
string puzzle[];};

loadPuzzle function loadPuzzle函数

void loadPuzzle(puzzle p){
char c;
p.puzzle[5];
for(int i = 0 ; i <p.rows ; i++){
   p.puzzle[0] = "                      ";
   for(int j = 0 ; j<p.cols ; j++){
      iFS >> c;
      if(!c=='\0')
         p.puzzle[i][j]=c;
   }
 }
 }

main function 主功能

int main(int agrc, char* args[]){
//setting default file name to make it easier for testing
string sourceFile = "testfile.txt";
puzzle p;
puzzle *puzz = &p;
//space left to add another do if need be
   do{
      cout << "please enter scramble name: ";
      getline(cin, sourceFile);
      cout << endl;
      iFS.open(sourceFile.c_str());
      if(!iFS.is_open()){
         cerr << "Couldnt open file" << endl;
      }
   }while(!iFS.is_open());
p.cols = getPuzzleCols();
p.rows = getPuzzleRows();
cout << p.rows << p.cols;
loadPuzzle(p);
// displayPuzzle(p);  
}

While you can declare an array with no size 虽然可以声明没有大小的数组

struct puzzle {
int cols;
int rows;
string puzzle[];};

You can't give it a size later through p.puzzle[5]; 稍后无法通过p.puzzle[5];它的大小p.puzzle[5]; . This line doesn't actually do anything. 该行实际上不执行任何操作。

Instead what the no-sized array does is allows one to access memory beyond the end of the struct as if it were an array. 相反,什么没有大小的数组做是允许你访问的内存超越结构的结尾好像它是一个数组。 This can be useful for clever/old-school ways of allocating arrays, but isn't good for modern C++. 这对于巧妙/过时的分配数组方法可能很有用,但对现代C ++不利。

What you should do instead is learn to use std::vector . 相反,您应该做的是学习使用std::vector

Start with: 从...开始:

struct puzzle {
int cols;
int rows;
std::vector<string> puzzle;};

Then read up on how to add elements to it (such as resize or push_back ). 然后阅读如何向其中添加元素(例如resizepush_back )。

Or if you can't do that for some reason, then you need to give the array its size in its declaration so that it really exists. 或者,如果由于某种原因而无法执行此操作,则需要在数组的声明中为其指定大小,以使其真正存在。 For example: 例如:

struct puzzle {
int cols;
int rows;
string puzzle[5];};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM