c - 二维数组添加额外的字符

标签 c arrays

这是我的代码,用于附加到二维数组并将其逐行显示到网格中。

void map_print() {

    char map[head->xdim][head->ydim]; // Generate 2D array for map
    memset( map, 0, sizeof(map));

    FEATURE *temp=head->next; // Get the pointer of the head of linked list

    while(temp!=NULL) // Generated the map with the features
    {
        for (int xdim = 0; xdim < temp->xdim; xdim++){
            map[temp->yloc][temp->xloc + xdim] = temp->type;
            printf("X axis: Appeding to map[%d][%d]\n",temp->yloc,temp->xloc+xdim);
        }
        for (int ydim = 0; ydim < temp->ydim; ydim++){
            map[temp->yloc + ydim][temp->xloc] = temp->type;
            printf("Y axis: Appeding to map[%d][%d]\n",temp->yloc + ydim,temp->xloc);

        }
        temp=temp->next;
    }

    for (int i = 0; i < head->ydim; i++) { // Print out the map
        for (int j = 0; j < head->xdim; j++) {
            //printf("%c ", map[i][j]);
            printf("map[%d][%d](%c)",i,j,map[i][j]);
        }
        printf("\n");
    }
}

enter image description here

基于 printf,它应该只附加到以下坐标。但是,map(1)(4)、map(2)(4)、map(3)(4)、map(4)(4) 正在打印我没有附加到它的 *。

我找不到任何添加该额外字符的代码行

最佳答案

你混合了 x 和 y。声明是char map[head->xdim][head->ydim]; ([x][y]),但你像一样使用它map[temp->yloc][temp->xloc + xdim] = temp->type; ([y][x]).

如果您的数组大小为 [10][5] 并且您正在访问 [0][9] 它将调用未定义的行为(因为越界访问) 并且一种可能性是它将访问 [1][4](二维数组中的第十个元素)。

关于c - 二维数组添加额外的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535094/

相关文章:

c - 有人可以解释一下代码吗?

创建固定大小数组的每个可能值

c - 访问结构成员时返回字节,打印结构变量地址时发生段错误

arrays - apple swift - 从变量引用数组

php - 使用关联数组进行数组推送

java - 测试表的最大值时出错?

c++ - 向旧的 C++ 意大利式编码器介绍 MVC?

java - 为什么 Java 只接受字符串格式的输入?

java - 如何在 java 中将 char[][] 转换为 Character[][]

python - 查找所有字符串拆分组合