将二维字符数组初始化为全空白时出现问题
Having trouble initializing a two-dimensional character array to all white space
当我使用此代码时:
#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;
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 无法通过空白将文本文件行分隔为矢量
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- ::MoveWindow的问题——留下空白
- 将二维字符数组初始化为全空白时出现问题