c - 用短语 Apples 替换矩阵中的所有空值

标签 c matrix

我的问题是,我想通过用短语“Apples”替换它们来摆脱 null。如果有人可以查看我的代码并告诉我哪里出了问题以及我可以应用什么修复来完成该任务,那就太好了。

输入(文本文件):

A B C

E F G

I J K L

char *map[10][10];
int loadMap(char * filename){
    FILE *fp;
    int row = 0;
    int col= 0;

    char buffer[1000];
    char phrase[100] = "pass";

    fp = fopen(filename,"r");
    if(fp == NULL){
      perror(filename);
      return(1);
 }

 char ch;
while (1) {
    fscanf(fp, "%s", buffer);

    map[row][col] = (char *)malloc(sizeof(char) * (strlen(buffer) + 1));

    strcpy(map[row][col], buffer);

    ch = fgetc(fp);

    if (ch == ' ') {
        col += 1;
    }
    else if (ch == '\n') {
        row += 1;
        col = 0;
    }
    else if (ch == EOF) {
        break;
    }
}

 return(0);
}
void DisplayMap(int size){

  int row, columns;

  for (row=0; row<DUNGEONSIZE; row++)
  {
      for(columns=0; columns<DUNGEONSIZE; columns++)
           printf("%s  ", map[row][columns]);
      printf("\n");
   }
  }

输出:

A  B  C  (null)  (null)  (null)  (null)  (null)  (null)  (null)
E  F  G  (null)  (null)  (null)  (null)  (null)  (null)  (null)
I  J  K  L  (null)  (null)  (null)  (null)  (null)  (null)
L  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)
(null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)
(null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)
(null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)
(null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)
(null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)
(null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)  (null)

最佳答案

看来您的问题出在显示尺寸函数上。它会增加到数组( map )的大小。您没有到达的所有元素(由于切换行/行)都未初始化,在本例中为 NULL。

显示时,要检查并确保它不为 NULL。如果 map 被声明为全局变量,您应该在显示之前检查它是否为空(即 if(map[x][y] == NULL...)。如果它不是t,您将必须如下所示填充数组。

顺便说一句:正如@kaylum 所说,在显示函数中使用 printf("%s ", map[row][columns] ? map[row][columns] : "Apples");如果 map 是全局的必须有效的方法。

现在,如果您想改用苹果。在你的填充函数中,当你看到一个新行时,从该索引运行直到结束并用苹果填充。然后在找到文件末尾后,用 apple 填充剩下的所有内容:

while{...
 else if (ch == '\n') {
    while (col < 10){ //or col < sizeof(map[0])/sizeof(map[0][0])
       col++
       //malloc map here
       strcpy(map[row][col], "Apple"); }
    row += 1;
    col = 0;
 }...}
 for (; row < 10; row++){ 
  for(; col < 10; col++){ 
    //malloc map[row][col] here
    strcpy(map[row][col],"APPLE");} 
    col = 0;}

关于c - 用短语 Apples 替换矩阵中的所有空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38066931/

相关文章:

c - 如何从通过指针调用函数的函数返回指针到返回指针的函数?

matplotlib - 如何将多个 matshow() 结果放在一张图中?

c++ - 从没有二维数组的矩阵文件中读取坐标?

python - numpy 矩阵乘法逐行

algorithm - 矩阵中的最大路径成本

c - 如何处理计算器溢出?

c - 为什么局部变量不匹配全零条件?

c - 打印字长数组未按预期工作

matlab - 在 Matlab 中使用 accumarray 对数据求和

c - C中的多线程程序中哪些信号不应该被线程阻塞?