【问题标题】:Having trouble initializing a two-dimensional character array to all white space将二维字符数组初始化为所有空格时遇到问题
【发布时间】:2014-06-11 02:48:36
【问题描述】:

当我使用这段代码时:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

void InitBoard(char boardAr[][3])
{
    boardAr[3][3] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
}

我收到此错误:

cannot convert '<brace-enclosed initializer list>' to 'char' in assignment

【问题讨论】:

    标签: c++ arrays function whitespace multidimensional-array


    【解决方案1】:

    您可以通过以下方式使用值初始化多维数组 (c++)。

    char boardAr[3][3] =
    {
        {' ', ' ', ' '},
        {' ', ' ', ' '},
        {' ', ' ', ' '}
    };
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      您正在尝试使用带有赋值的初始化程序。您只能使用带有初始化的初始化程序。你试图做的事情是不可能的。

      【讨论】:

        【解决方案3】:

        声明

        boardAr[3][3] = ...
        

        是对 boardAr 第四行第四列的​​赋值。这不是对数组本身的赋值。

        如果您想有效地将​​整个内存范围初始化为已知值,可以使用 memset 或 memcpy。

        【讨论】:

          【解决方案4】:
          #include <iostream>
          #include <iomanip>
          #include <string>
          using namespace std;
          
          void InitBoard(char boardAr[][3])
          {
              for (int i = 0; i < 3; i++)
              {
                  for (int j = 0; j < 3; j++)
                  {
                      boardAr[i][j] = ' ';
                  }
              }
          }
          

          这是初始化数组的正确方法

          【讨论】:

            【解决方案5】:

            C 中没有二维数组,内部二维数组是一维数组。考虑到这一事实,我们可以使用 memset() 来初始化 2D 数组或任何结构或任何具有连续内存布局的东西。 please refer here

            void InitBoard(char boardAr[][3], const int row, const int col)
            {
                memset(boardAr, ' ', sizeof(char)*row*col); // you can use any other value also, here we used ' '.  
            }
            
            void main(int argc, char* argv[])
            {
                char arr[3][3];
                InitBoard(arr, 3,3); // It initialize your array with ' '
                return 0;
            }
            

            【讨论】:

              猜你喜欢
              • 2011-02-17
              • 1970-01-01
              • 2020-11-22
              • 1970-01-01
              • 2014-05-14
              • 2011-06-04
              • 1970-01-01
              • 1970-01-01
              • 2016-11-12
              相关资源
              最近更新 更多