【问题标题】:Populating 2D char array leads to crash in C填充 2D 字符数组会导致 C 崩溃
【发布时间】:2013-01-09 18:37:32
【问题描述】:

我正在尝试使用文本文件中的字符填充二维数组 (mapLayout)。

当我在读取字符时使用 printf 输出字符时,一切看起来都很好,但是将字符添加到数组的实际行似乎导致了崩溃。

#include <stdio.h>
#include <stdlib.h>

void createMap();

//height of file being read
int mapHeight, mapWidth = 20;
char mapLayout[20][20];

int main()
{
    createMap();
    return 0;
}

//read in string from file and populate mapLayout with chars
void createMap(){
    FILE *file = fopen("map.txt", "r");
    int col, row = 0;
    int c;

    if (file == NULL)
        return NULL; //could not open file

    while ((c = fgetc(file)) != EOF)
    {
        printf("%c", c);
        printf("\nx:%d, y:%d\n", col, row);

        if(c == '\n'){
            row++;
            col = 0;
        }else{
            mapLayout[col][row] = c;        //<--  This line seems to be the problem
            col++;
        }

    }

    return;
}

我正在阅读的文件是 20 x 20 的地图表示。这里是:

xxxxxxxxxxxxxxxxxxxx
xA                 x
x                  x
x                  x
xxxxxxxxxxxxxxxx   x
x                  x
x                  x
x                  x
x                  x
x                  x
x    xxxxxxxxxxxxxxx
x           x      x
x           x      x
x           x      x
x           x      x
x           x      x
x     xxxxxxx      x
x                  x
x                 Bx
xxxxxxxxxxxxxxxxxxxx

任何帮助将不胜感激。

【问题讨论】:

  • 您在代码中将列视为行。
  • C 固定数组是行优先的。一个[行][列]。
  • 您是否使用调试器逐步完成此操作并检查rowcol 是否具有您预期的值?
  • 嗯,有 printf("\nx:%d, y:%d\n", col, row); - 我想有 some 输出;这是什么?
  • 您的CreateMap 被声明为返回void,但返回NULL。它在这里正常工作,但没有错误检查。如果要将映射的每一行视为字符串,则应确保映射的每一行都正确地以 NUL 终止(map 变量是一个全局数组,C 保证它将以零填充,但如果你重用它无论如何,这无济于事)。您的行正好有 20 个字符长,因此您需要空间。你初始化了row,而不是col

标签: c arrays multidimensional-array char


【解决方案1】:

int col, row = 0; 为什么col 未初始化为零。如果文件中的第一个字符是\n,那么它不会崩溃,对于所有剩余的情况,都会发生崩溃(未定义的行为)。

int col = 0;
int row = 0;

【讨论】:

  • 完美,谢谢!我显然需要更加熟悉 C。
【解决方案2】:

根据您的编译器,可能是该行和 mapHeightd 开始时没有获得 anny 值。 尝试: int 行=0,列=0;

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2015-07-27
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多