簡體   English   中英

將結構傳遞給函數以編輯數組導致C ++ seg錯誤

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

我正在做一個打單詞游戲的項目,目前正在將字母放入一個字符串數組中。 當前不使用任何指針,我擔心這是原因,但在這一點上我很困惑,因為我的作業要求我使用結構。

任何幫助將不勝感激,謝謝。

結構定義:

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

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;
   }
 }
 }

主功能

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);  
}

雖然可以聲明沒有大小的數組

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

稍后無法通過p.puzzle[5];它的大小p.puzzle[5]; 該行實際上不執行任何操作。

相反,什么沒有大小的數組做是允許你訪問的內存超越結構的結尾好像它是一個數組。 這對於巧妙/過時的分配數組方法可能很有用,但對現代C ++不利。

相反,您應該做的是學習使用std::vector

從...開始:

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

然后閱讀如何向其中添加元素(例如resizepush_back )。

或者,如果由於某種原因而無法執行此操作,則需要在數組的聲明中為其指定大小,以使其真正存在。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM