我正在编写一个函数,它将文本文件的内容(排列成表格)复制到一个2D数组中,只是没有空格。
A B C
D E F
G H I
则生成的数组将等效于
char tableArray[ROWS][COLS] = {{'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'I'}};
我在初始化上述数组时遇到问题。
该函数当前如下所示:
#define ROWS 3
#define COLS 3
char tableArray[ROWS][COLS];
//proper initialization of tableArray here. Not sure what to put
void copyTable(){
//copies the characters of the table into an array
FILE *fp = fopen("table.txt", "r");
if (fp == NULL) {
printf("No file found.");
return;
}
char c;
int currentRow;
int currentCol;
//Iterate through the file character by character
for (currentRow = 0; currentRow < ROWS; currentRow++) {
for (currentCol = 0; currentCol < COLS; currentCol++) {
c = fgetc(fp);
if (!(c == ' ')) {
tableArray[currentRow][currentCol] = c;
}
fgetc(fp); //skip newline character at end of row
}
}
tableArray[ROWS][COLS] = '\0';
}
但是由于内存分配不足,这段代码无法工作。
char tableArray[ROWS][COLS];
int** tableArray;
tableArray = (int**)malloc(ROWS * sizeof(int*));
for (int i = 0; i < ROWS; i++) {
tableArray[i] = (int*)malloc(COLS * sizeof(int));
}
但我并不真正理解这段代码的作用,它会产生一个错误:'tableArray'没有命名型别,我无法修正这个问题。
那么如何正确初始化tableArray呢?如果函数中还有其他问题,与这部分无关,请告诉我。
1条答案
按热度按时间piwo6bdm1#
当我们知道数据维度(例如3x3)时,调用一个函数来处理分配和阅读。
分配给引用的对象,而不是分配给类型。更易于正确编码、检查和维护。
测试分配是否成功。
用
fgetc()
读取并测试。使用
size_t
调整大小和建立索引。我建议使用
unsigned char
作为数据类型,因为char
中保存的内容更清楚,但可以使用任何您想要的类型。