c - 不使用 for 循环打印矩阵

标签 c string matrix printing puts

我正在尝试使用单个放置而不是嵌套循环来打印字符矩阵,但我总是在打印结束时多得到一个字符。我要做一个乒乓球游戏,我需要尽快更新屏幕。

void main()
{
    int x, y;
    char map[40][80];

    for(y=0; y<40; y++)
    {
        for(x=0; x<80; x++)
        {
            map[y][x]='o';    //Just for testing.
        }
    }
    puts(map);
}

使用此代码打印的最后两行是:

ooooooooooooo...o (80 'o's)
<

最佳答案

#include <stdio.h>

int main(int argc, char **argv)
{
    int x, y;
    char map[40*80+1];

    for(y=0; y<40; y++) {
        for(x=0; x<80; x++) {
            map[y*80+x]='o';
        }
    }
    map[40*80] = '\0';
    puts(map);

    return 0;
}

我已将 map 更改为线性数组。这样可以更轻松地添加 \0最后关闭字符串。没有 \0puts()命令不知道何时停止打印。在你的情况下,这只是一个 < ,但它可能会导致打印很多字符!

此外,我不会依赖多维数组在内存中线性映射的事实。

关于c - 不使用 for 循环打印矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30288190/

相关文章:

c - Autoconf 问题 : “error: C compiler cannot create executables”

c - 试图将 C 程序翻译成 x86 汇编

python - 输出 HTML 无序列表 python

c - 错误 : expected '=' , ','、 ';'、 'asm' 或 '__attribute__' token 之前的 '*'

string - typescript :强制类型为 "string literal"而不是 <string>

java - System.out.printf() 用法

计算旋转矩阵以将 vector (1,1,1) 与 vector 对齐

python - 每行的 Bin 元素 - NumPy 的矢量化 2D Bincount

r - 取矩阵 r 中行的平均值

c - 有没有比 select() 和 poll() 更快的非阻塞方法来检查数据?