c - 将数据保存到 malloc 的 2dim 数组在 C 中不起作用

标签 c arrays malloc pacman

我正在用 C 编写一个简单的游戏。所以我试图将一些数据保存到我正确 malloc 的 2dim 数组中。问题是当我想将我写入的那个变量传递给另一个函数时。

int readMap(FILE *eingabe, map_t *map, config_t *configstruct, pacman_t *pacman)
{
  int i = 0, j = 0, k = 0, pac = 0;
  map->mapdesign = (char**) malloc(sizeof(char*) * map->height);
  do
  {
    for (i = 0; i < map->height; i++)
    {
      map->mapdesign[i] = (char*) malloc(sizeof(char) * (map->width + 1));
      for (j = 0; j < map->width; j++)
      {
        fscanf(eingabe, "%c", &map->mapdesign[i][j]);
        printf("%c", map->mapdesign[i][j]);
        if (map->mapdesign[i][j] == configstruct->ghost)
          map->ghostcount++;
        else if (map->mapdesign[i][j] == configstruct->foodtypes[0]
            || map->mapdesign[i][j] == configstruct->foodtypes[1])
        {
          map->foodcount++;
        }
        for (k = 0; k < PAC; k++)
        {
          if (map->mapdesign[i][j] == configstruct->pacman[k])
          {
            pacman->cordinate.x = j;
            pacman->cordinate.y = i;
            if (pac > 1)
              return -1;
            pac++;
          }
          k++;
        }
      }
    }
  } while (!feof(eingabe));
  return 0;
}

当我在函数本身中使用 printf 时,它会打印出我想要的内容。然后我决定我想使用一个函数来为我打印出来,看起来像这样:

int renderMap(map_t *mapstr)
{
  int i = 0;
  clrscr();
  for (i = 0; i < mapstr->height; i++)
    puts(mapstr->mapdesign[i]);
  return 0;
}

上面的这个函数应该打印出:

Pastebin 1

但它实际上打印了这个:

Pastebin 2

提前致谢!

最佳答案

我建议首先了解 printf 和 puts 这两个函数之间的区别,因为它们对字符终止的处理方式不同。这可能是错误。

或者把相对完整的代码发过来,让两个函数独立运行我会调试返回给你。

关于c - 将数据保存到 malloc 的 2dim 数组在 C 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27318949/

相关文章:

c - 在其他文件中的结构/数组上使用 malloc

c - 使用 %f 打印整型变量

arrays - ELM 如何解码 json 数组中的不同值

java - 从文本文件中获取单行和多行值

c - C中的动态程序

malloc - 如何对 malloc 实现进行基准测试?

c - setjmp 和 GCC 的合法使用

C - 为什么这个程序打印两个 0?

c - 线程与互斥体同步

php - 在表格行内检查条件时更改背景颜色不起作用