【问题标题】:Trash output in 8x8x2 array in CC中8x8x2数组中的垃圾输出
【发布时间】:2021-07-12 06:26:17
【问题描述】:

我正在尝试表示一个 8x8 笛卡尔平面,其内容将是长度为 2 的字符串。我想尽可能地保持这种方案的类型安全并这样做:

typedef char cartesian[8][8][2];
cartesian xy;

for(int i=0; i<8; i++){
        for(int j=0; j<8; j++){
                xy[i][j][0] = ' '
                xy[i][j][1] = ' '
        }
}

// The first element would represent some kind of information, and the other one 
// would be just elements like '+' or '*'. In other cases, this would be 'EMPTY',
// it means a double space.

xy[2][4][0] = 'B';
xy[2][4][1] = '+';

// The right printing method (cause it doesn't have any trash) would be:

for(int i=0; i<8; i++){
        for(int j=0; j<8; j++){
                printf("| %c%c ", xy[i][j][0], xy[I][j][1] );
        }
        printf("|\n");
}

但问题是:为什么输出垃圾带有 printf("| %s ", xy[i][j][]); ? 我知道这可能是个愚蠢的问题,但我现在累了。

提前致谢。

顺便说一句,分配不起作用。我的意思是:xy[2][4][] = "B+";

【问题讨论】:

  • "长度为 2 的字符串。C 中的字符串需要以 NUL 结尾。两个字母的字符串需要 三个 字符来存储。更改 @ 987654324@ 到 [3] 并确保 xy[i][j][2] 设置为 0
  • 分配无效”。除非在初始化程序中使用,否则不能将字符串文字分配给数组。请改用strcpy
  • 乍一看,您似乎将字符串与字符混淆了。 C 中没有真正的字符串数据类型,只有最后一个必须为 NUL 的字符数组。您应该编辑您的问题以添加您使用的矩阵的表示形式。
  • @kaylum 我认为[2] 是对的,原因之一是\0 对吗?另一方面,这个怎么样:typedef char string[LENGHT] 然后string str = 'This would have sense?';
  • @fpiette 取了第一对for 之类的初始化器 你的意思是必须做xy[i][j][2] = NULL 吗?我不明白。

标签: c multidimensional-array


【解决方案1】:

这是您重写的代码。请注意,cartesian 现在是 [8][8][3] 并且 strcpy 用于填充最后一个数组维度。为了清楚起见,我将 xy 清除为一个单独的函数。

#include <stdio.h>
#include <string.h>

typedef char cartesian[8][8][3];

void clearXY(cartesian *xy)
{
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            strcpy((*xy)[i][j], "  ");
        }
    }
}

int main(int argc, char *argv[])
{
    cartesian xy;

    // The first element would represent some kind of information, and the other one 
    // would be just elements like '+' or '*'. In other cases, this would be 'EMPTY',
    // it means a double space.
    clearXY(&xy);

    strcpy(xy[2][4], "B+");

    printf("-------- Method 1 --------\n");
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            printf("| %c%c ", xy[i][j][0], xy[i][j][1]);
        }
        printf("|\n");
    }

    printf("-------- Method 2 --------\n");
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            printf("| %s ", xy[i][j]);
        }
        printf("|\n");
    }
    printf("-------- Done ------------\n");
}

【讨论】:

  • 绝对清楚,但我不清楚[3]。我假设[0][1] 将设置数据,最后一个[2] 将设置\0。这已经足够了。为什么需要[3]?即使我已经用strncpy() 证明了你的示例代码,它也适用于 3,但 2 是相同的垃圾输出。我这样做是因为 strcpy() 被认为有点警告。
  • @Karl,3 是 char 数组的维度。每个字符串包含多少个字符? [0][1][2] 所以需要 3 个元素。请注意,从 0 开始索引,如果大小为 3,则访问 arr[3] 是非法的。您最多可以访问索引size-1