用C打印网格

问题描述 投票:0回答:1

我正在尝试在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);

}
c arrays grid
1个回答
1
投票
  1. 首先,你应该将"-"改为'-'。因为"-"是一个字符串并且隐含地包含'\0'。因此"-"长度为9,因为字节长度为8。
  2. 您应该将print: printf("%-5d", row[i][j]); 更改为: printf("%-5c", row[i][j]);
© www.soinside.com 2019 - 2024. All rights reserved.