2

过去 4 个小时左右我一直在研究这个问题,但不知道该怎么做。我正在将我的 Game of Life 移植到 C,但无法让 FileIO 正常工作。输入文件的格式为:

Game 1: Pattern Name
10 20
// Pattern here
Game 2: Pattern Name
15 25
// Pattern here

依此类推,直到文件结束。10我想要做的是打印游戏,并为第一个游戏创建一个大小的多维数组20,然后将模式存储在这个数组中。这是我到目前为止所拥有的:

void fileIO() {
    FILE *file;
    char buffer[BUFFER_SIZE];
    int rows = 0, cols = 0;

    file = fopen("input.txt", "r");

    if(file == NULL) {
            printf("Error opening file.");
    } else {
            while(fgets(buffer, BUFFER_SIZE, file) != NULL) {
                    if(strstr(buffer, "Game") != NULL) {
                            printf("%s", buffer);
                    } else {
                            sscanf(buffer, "%d%d", &rows, &cols);
                    }
            }
            fclose(file);
    }
}

这就是我碰壁的地方,遇到了一系列问题,

Creating a dynamic global multi-dimensional array

Preventing the buffer from reading into the next game

我认为最好的方法是为每个游戏创建一个结构数组,例如,

struct game {
    char board[][];
};

struct game games[];

但是,我不知道如何动态设置每个行和列的数量的参数。

4

1 回答 1

3

我是一个相对较新的 C 程序员,但我认为我可以帮助处理动态数组。C 在编译期间初始化数组,如果您需要动态设置它们,这将不起作用。因此,不要使用如下符号:

char board[][];

您需要使用指针并根据所需的数组大小为其分配内存。这是使用 malloc 函数完成的。例如:

#include<stdlib.h>

int i;
char **board;
board = malloc(rows * sizeof board[0]);

for(i = 0; i<rows; i++){
board[i] = malloc(columns * sizeof board[0][0]);

如果您还没有了解指针和内存分配,那么我不确定这是否会对您有很大帮助。我不完全理解你想要做什么,所以我不能给你一个具体的代码示例,但这是一种更通用的动态分配数组的方法。就像我说的那样,我是 C 的初学者,所以如果这没有帮助,我深表歉意。这是一个很好的链接,有助于理解指针。

http://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays

于 2013-10-20T00:16:37.950 回答