You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何打印C++ char矩阵?新手求助排查代码错误

问题分析与修正

你的代码里有两个关键错误导致无法正确打印char矩阵:

  • 索引越界:循环中你一直访问matrix[sizeX][sizeY],这是数组的越界位置(数组索引从0开始,sizeX为3时,有效行索引是0-2,列同理),应该用循环变量i和j访问对应位置的matrix[i][j]。
  • 格式符错误:printf("%d", ...)会输出字符的ASCII码值,要打印字符本身,需改用%c格式符。

另外,你给每行末尾添加的'\0'在逐个打印字符的场景下没必要,不过保留也不影响运行。

修正后的基础版本代码

#include <iostream>
using namespace std;

int main() {
    const int sizeX = 3;
    const int sizeY = 3;

    char matrix[sizeX][sizeY] = { {'a','b','c'},{'d','e','f'},{'g','h', 'k'}};

    for (int i = 0; i < sizeX; i++)
    {
        for (int j = 0; j < sizeY; j++)
        {
            printf("%c ", matrix[i][j]);
        }
        cout << endl;
    }
    
}

若保留原数组尺寸的修正版本

如果你坚持要保留sizeX+1和sizeY+1的数组定义,修正后代码如下:

#include <iostream>
using namespace std;

int main() {
    const int sizeX = 3;
    const int sizeY = 3;

    char matrix[sizeX+1][sizeY+1] = { {'a','b','c', '\0'},{'d','e','f', '\0'},{'g','h', 'k', '\0'}};

    for (int i = 0; i < sizeX; i++)
    {
        for (int j = 0; j < sizeY; j++)
        {
            printf("%c ", matrix[i][j]);
        }
        cout << endl;
    }
    
}

更简洁的整行打印方式

利用你添加的'\0',可以省略内层循环直接打印整行:

#include <iostream>
using namespace std;

int main() {
    const int sizeX = 3;
    const int sizeY = 3;

    char matrix[sizeX+1][sizeY+1] = { {'a','b','c', '\0'},{'d','e','f', '\0'},{'g','h', 'k', '\0'}};

    for (int i = 0; i < sizeX; i++)
    {
        printf("%s\n", matrix[i]);
    }
    
}

内容的提问来源于stack exchange,提问作者Crystal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:35:23