【发布时间】:2013-05-27 10:39:18
【问题描述】:
有问题的代码旨在从 txt 文件加载数据,该文件稍后将用于玩康威人生游戏的控制台版本。数据类型是字符串的二维数组,因此可以存储生命游戏的进一步迭代,以检查振荡模式。它通过引用将数组传递给“readworld”函数。它从文本文件的顶部加载未来数组的迭代次数、宽度和高度。
此代码的问题在于它从文本文件加载并成功地将其保存在“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函数... -
三重指针会灼伤我们……它会灼伤我们!
-
您需要通过指针...或引用传递三重指针,以便重新分配它。
-
@Dukeling:问题被标记为 C,所以我猜没有参考...
-
@OliCharlesworth 哦,对了,我总是忘记 C.
标签: c string memory-management segmentation-fault dynamic-memory-allocation