打印char类型矩阵输出异常,求排查扫雷游戏代码问题
扫雷游戏矩阵异常字符问题解决方案
核心错误分析
- 字符赋值错误:你给
char类型的field[i][j]赋值了字符串字面量"a",这是一个指向字符数组的指针(地址),而非单个字符。把指针地址的低字节存储到char变量中,会导致输出乱码(如Õ)。正确的单个字符需用单引号包裹:'a'。 - 打印循环边界错误:第二个嵌套循环中,j的终止条件写成了
j < numRows,实际应是j < numCols。若选择专家难度(30列16行),该错误会导致只打印16列而非30列,破坏矩阵完整性。
修正后的代码
#include <stdio.h> #include <stdlib.h> int selectDifficulty(){ int d; do{ printf("--------Selezionare difficolta' del campo minato--------\n"); printf("1: Principiante (9x9)\n"); printf("2: Intermedio (16x16)\n"); printf("3: Esperto (30x16)\n"); printf(">>>: "); scanf("%d", &d); }while(d<1 || d>3); return d; } int main(){ int d,numCols,numRows; d = selectDifficulty(); //Create numRows x numCols matrix based on difficulty d if(d==1){ numCols=9; numRows=9; } else if (d==2){ numCols=16; numRows=16; } else{ numCols=30; numRows=16; } char field[numRows][numCols]; for(int i = 0; i < numRows; i++){ for(int j = 0; j < numCols; j++){ field[i][j] = 'a'; // 改为单引号包裹的单个字符 } } for(int i = 0; i < numRows; i++){ for(int j = 0; j < numCols; j++){ // 修正循环边界为numCols printf("%c",field[i][j]); } printf("\n"); } return 0; }
内容的提问来源于stack exchange,提问作者VittorioDL
相关产品推荐
相关产品推荐

