将二维字符数组初始化为全空白时出现问题

Having trouble initializing a two-dimensional character array to all white space

本文关键字:空白 问题 初始化 数组 字符 二维      更新时间:2023-10-16

当我使用此代码时:

#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++(。

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

希望这能有所帮助!

您正试图使用带有赋值的初始化程序。您只能将初始化程序与初始化程序一起使用。你想做的事是不可能的。

语句

boardAr[3][3] = ...

是对第四行板Ar的第四列的分配。这不是对数组本身的赋值。

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

#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] = ' ';
        }
    }
}

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

在C中没有什么比2D数组更好的了,内部2D数组是1D数组。考虑到这个事实,我们可以使用memset((初始化2D数组或任何结构或任何具有连续内存布局的结构。请参考这里的

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;
}