在 C 语言中打印网格



我正在尝试用 C 语言打印一个网格,以便稍后在其上移动一个对象。输出应该是这样的:

- - -
- - -
- - -

但是我一直收到错误excess elements in char array initializer,我不知道为什么,有什么建议吗?

#include <stdio.h>
#define X 3
#define Y 3
// Print the array
void printArray(char row[][Y], size_t one, size_t two)
{
// output column heads
printf("%s", "       [0]  [1]  [2]");
// output the row in tabular format
for (size_t i = 0; i < one; ++i) {
// output label for row
printf("nrow[%lu] ", i);
// output grades for one student
for (size_t j = 0; j < two; ++j) {
printf("%-5d", row[i][j]);
} 
} 
} 
int main(void)
{
// initialize student grades for three students (rows)
char row[X][Y] =  
{ { "-", "-", "-"},
{ "-", "-", "-"},
{ "-", "-", "-"} };
// output the row
puts("The array is:");
printArray(row, X, Y);
}
  1. 首先,您应该将"-"更改为'-'。因为"-"是一个字符串,并且隐式包含''。所以"-"长度是 9,因为字节长度是 8。
  2. 您应该更改打印: printf("%-5d", row[i][j]); 自: printf("%-5c", row[i][j]);

最新更新