0

有問題的代碼旨在從txt文件加載數據,該文件稍後將用於播放Conways Game of Life的控制檯版本。數據類型是字符串的二維數組,因此可以存儲生命遊戲的進一步迭代以檢查振盪模式。它通過引用將數組傳遞給「readworld」函數。它從文本文件的頂部加載未來數組的迭代次數,寬度和高度。C 2D字符串數組導致在聲明的函數外發生分段錯誤

該代碼的問題在於它從文本文件加載並將其成功保存在「loadWorld」函數中。通過在函數結尾打印輸出證明了這一點。但是當在「main」函數中訪問相同的數組時,會在第一個元素處發生分段錯誤。

這是奇怪的,因爲的malloc分配的內存應該在堆上進行分配,因此課稅其他功能,除非我失去了一些東西......

林不知道我是否應該發佈文字文件,但如果我應該,留下評論,它會被張貼。

任何幫助將不勝感激!

註釋 使用MinGW 4.7.2編譯文件。 文本文件的第一行包含要執行GOL的列數,行數和迭代次數。 文本文件中的x代表活細胞,而空格代表死細胞。

#include <stdio.h> 
#include <stdlib.h> 

void readworld(char ***,int *,int *,int*); 

int main(){ 
    int rows,columns,ticks,repetition,count,count2; 
    char ***world; 
    readworld(world,&rows,&columns,&ticks); 
    printf("Rows: %i Columns: %i Ticks: %i\n",rows,columns,ticks); 
    for(count = 1; count < rows-1; count++){ 
     //Segmentation fault occurs here.      
     printf("%s",world[0][count]); 
    } 

    system("PAUSE"); 
    return 0; 

} 

void readworld(char ***world,int *rows,int *columns,int *ticks){ 
    FILE *f; 
    int x,y; 


    //Load the file 
    f=fopen("world.txt","r"); 
    //Load data from the top of the file. 
    //The top of the file contains number of rows, number of columbs and number of iterations to run the GOL 
    fscanf(f,"%i %i %i\n", rows, columns, ticks); 

    printf("%d %d %d\n",*rows, *columns, *ticks); 

    *columns=*columns+2; //Includes new line and end of line characters 
    world=(char***) malloc(*ticks*sizeof(char**));  //makes an array of all the grids 

    for (y=0;y<*ticks;y++){ 

     world[y]=(char**) malloc(*rows * sizeof(char*)); //makes an array of all the rows 

     for (x=0;x<*rows;x++){ 
      world[y][x]=(char*) malloc(*columns * sizeof(char)); //makes an array of all the collumns 
     } 
    } 

    for (y=0;y<*rows;y++){ 
     fgets(world[0][y],*columns,f); //fills the array with data from the file 
    } 
    //Correctly prints the output from the textfile here 
    for (y = 0 ; y < *rows; y++) 
      printf("%s",world[0][y]); 
} 
+2

你傳遞一個** **複製的'world'到'readworld'功能... –

+1

三重指針燃燒我們......它燃燒美! – aardvarkk

+0

您需要通過指針...或通過引用傳遞三元指針,以便您可以重新分配它。 – Dukeling

回答

1

當你傳遞一個對象到一個函數,您的計算機創建對象的副本,併爲其分配相同的值。函數對複製對象的任何更改都不會應用於原始對象。

因此,在你的測試用例(應該是這樣)

#include <stdlib.h> 

void readworld(char ***); 

int main(){ 
    char ***world; 
    readworld(world); 
} 

void readworld(char ***world){ 
    world = malloc(42); 
} 

worldmainworldreadworld的(不同的)所做的更改的影響。您希望將指針傳遞給worldreadworld並修改指向的對象,類似於rows,columnsticks,如果您希望更改顯示在readworld之外。

int main(void) { 
    ... 
    readworld(&world,&rows,&columns,&ticks); 
    ... 
} 

void readworld(char ****world, int *rows, int *columns, int *ticks){ 
    ... 
    *world = malloc(42); 
    ... 
} 
+0

謝謝,你的解決方案工作! – jonahhooper