如何在C中初始化一个具有动态内存分配的二维字符数组?

qmelpv7a  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(148)

我正在编写一个函数,它将文本文件的内容(排列成表格)复制到一个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呢?如果函数中还有其他问题,与这部分无关,请告诉我。

piwo6bdm

piwo6bdm1#

当我们知道数据维度(例如3x3)时,调用一个函数来处理分配和阅读。
分配给引用的对象,而不是分配给类型。更易于正确编码、检查和维护。
测试分配是否成功。
fgetc()读取并测试。
使用size_t调整大小和建立索引。
我建议使用unsigned char作为数据类型,因为char中保存的内容更清楚,但可以使用任何您想要的类型。

unsigned char** read_char_matrix(FILE *inf, size_t rows, size_t cols) {
  unsigned char **table = malloc(sizeof table[0] * rows);
  if (table == NULL) {
    return NULL;
  }

  for (size_t c = 0; c < cols; c++) {
    table[c] = malloc(sizeof table[c][0] * cols);
    if (table[c] == NULL) {
      while (c > 0) {
        free(table[--c]);
      }
      free(table);
      return NULL;
    }
  }

  for (size_t r = 0; r < rows; r++) {
    for (size_t c = 0; c < cols; c++) {
      int ch = fgetc(inf);
      if (!isalpha(ch)) {
        TBD_Code_to_handle_error();
      }
      table[r][c] = (unsigned char) ch;
      ch = fgetc(inf);
      if (!isspace(ch)) {
        TBD_Code_to_handle_error();
      }
    }
  }
  return table;
}

相关问题