C++ 无法将二维字符数组初始化为全部空白
当我使用此代码时:C++ 无法将二维字符数组初始化为全部空白,c++,arrays,function,whitespace,multidimensional-array,C++,Arrays,Function,Whitespace,Multidimensional Array,当我使用此代码时: #include <iostream> #include <iomanip> #include <string> using namespace std; void InitBoard(char boardAr[][3]) { boardAr[3][3] = {' ',' ',' ',' ',' ',' ',' ',' ',' '}; } #包括 #包括 #包括 使用名称空间std; 无效初始板(字符板[][3]) { boar
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void InitBoard(char boardAr[][3])
{
boardAr[3][3] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
}
#包括
#包括
#包括
使用名称空间std;
无效初始板(字符板[][3])
{
boardAr[3][3]={'','','','','','','','','','','','','','','','''.'};
}
我得到这个错误:
无法在分配中将“”转换为“char”
您正在尝试将初始化器与赋值一起使用。您只能使用带有初始化的初始化器。你试图做的是不可能的。声明
boardAr[3][3] = ...
是对boardAr第四行第四列的赋值。它不是数组本身的赋值
如果您想有效地将整个内存范围初始化为已知值,可以使用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] = ' ';
}
}
}
#包括
#包括
使用名称空间std;
无效初始板(字符板[][3])
{
对于(int i=0;i<3;i++)
{
对于(int j=0;j<3;j++)
{
董事会[i][j]='';
}
}
}
这是初始化数组的正确方法您可以按以下方式使用值初始化多维数组(c++)
char boardAr[3][3] =
{
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
希望这有帮助 在C中没有什么比2D数组更好的了,在内部2D数组是1D数组。考虑到这一事实,我们可以使用memset()初始化2D数组或任何具有连续内存布局的结构或任何东西
char boardAr[3][3] =
{
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
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;
}