有問題的代碼旨在從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]);
}
你傳遞一個** **複製的'world'到'readworld'功能... –
三重指針燃燒我們......它燃燒美! – aardvarkk
您需要通過指針...或通過引用傳遞三元指針,以便您可以重新分配它。 – Dukeling