【问题标题】:C - Problems with 2D array [closed]C - 二维数组的问题[关闭]
【发布时间】:2016-05-03 05:22:44
【问题描述】:

我正在尝试使用 C 在命令行上打印某种笛卡尔坐标系。不幸的是,在尝试将特殊字符插入保存数据的指定二维数组时出现了一些问题。在一次循环运行期间(P 的第二/右行),有两个字符被插入到数组中:

有人对此有解决方案吗?

产生问题的部分代码(makeDots 填充数组):

#include <stdio.h>

#define WIDTH 20
#define HEIGHT 10

void makeDots(char a[WIDTH][HEIGHT]) {
    for (int x = 4; x < 7; x++) {
        int y = x + 1;
        //cartesian coordinate system - point of origin in bottom left corner
        a[y][x] = 'P';
        //a[i-1][WIDTH / 2 + i] = '+'; //try to remove misplaced P - leads to empty array
    }
}

void clear(char a[WIDTH][HEIGHT]) {
    for (int l = 0; l < HEIGHT; l++) {
        for (int c = 0; c < WIDTH; c++) {
            a[l][c] = '+';
        }
    }
}

void draw(char a[WIDTH][HEIGHT]) {
    for (int l = HEIGHT - 1; l >= 0; l--) {
        for (int c = 0; c < WIDTH; c++) {
            putchar(a[l][c]);
        }
        printf("\n");
    }
}

int main() {
    char a[WIDTH][HEIGHT];
    clear(a);
    makeDots(a);
    draw(a);
    return 0;
}

【问题讨论】:

  • 您的行索引和列索引混淆了。将[WIDTH][HEIGHT] 更改为[HEIGHT][WIDTH]

标签: c arrays multidimensional-array duplicates


【解决方案1】:

当访问数组时,您在函数 makeDots 中混合了 xy,在函数 cleardraw 中混合了 lc。像这样调整你的代码:

#define WIDTH 20
#define HEIGHT 10

void makeDots(char a[WIDTH][HEIGHT]) {
    for (int x = 4; x < 7; x++) {
        int y = x + 1;
        //cartesian coordinate system - point of origin in bottom left corner
        a[x][y] = 'P';
      //  ^  ^
        //a[WIDTH / 2 + i][i-1] = '+'; //try to remove misplaced P - leads to empty array
    }
}

void clear(char a[WIDTH][HEIGHT]) {
    for (int l = 0; l < HEIGHT; l++) {
        for (int c = 0; c < WIDTH; c++) {
            a[c][l] = '+';
          //  ^  ^
        }
    }
}

void draw(char a[WIDTH][HEIGHT]) {
    for (int l = HEIGHT- 1; l >= 0; l--) {
        for (int c = 0; c < WIDTH; c++) {
            putchar(a[c][l]);
                  //  ^  ^
        }
        printf("\n");
    }
}

int main() {
    char a[WIDTH][HEIGHT];
    clear(a);
    makeDots(a);
    draw(a);
    return 0;
}

【讨论】:

  • 谢谢,我现在可以正常使用了。
【解决方案2】:

查看您的以下代码:

void clear(char a[WIDTH][HEIGHT]) {
    for (int l = 0; l < HEIGHT; l++) {
        for (int c = 0; c < WIDTH; c++) {
            a[l][c] = '+';
        }
    }
}

您将 [WIDTH][HEIGHT] 用于您的 char 数组,但在 for 循环中,您使用的是相反的。看看它。这可能是问题所在。

【讨论】:

    猜你喜欢
    • 2018-07-31
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2021-04-08
    • 2017-04-11
    • 2021-10-24
    • 2020-01-18
    • 2021-04-09
    相关资源
    最近更新 更多