Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中打印2D字符数组+;_C++_Arrays_Char - Fatal编程技术网

C++ 在C+中打印2D字符数组+;

C++ 在C+中打印2D字符数组+;,c++,arrays,char,C++,Arrays,Char,所以我的代码有一个问题,我无法确定。简单地说,我想以一种网格格式打印出C++中的二维字符数组的内容。我的代码如下(请记住,我不想更改代码的结构,只要找出我没有得到预期结果的原因即可): #包括 #包括 使用名称空间std; 空抽板(炭板[3][4]) { int j=0; 对于(int i=1;i

所以我的代码有一个问题,我无法确定。简单地说,我想以一种网格格式打印出C++中的二维字符数组的内容。我的代码如下(请记住,我不想更改代码的结构,只要找出我没有得到预期结果的原因即可):

#包括
#包括
使用名称空间std;
空抽板(炭板[3][4])
{
int j=0;
对于(int i=1;i<12;i++)
{
如果((i%4)==1 | |(i%4)==2)
{
无法检查阵列范围:

char board[3][4]
那么你有:

board[i][j]  ->  board[1,2,3,5,6,7,9,10,11][j] 
无论
i%4
是什么,放入
board
的都是
i
而不是
i%3

使用以下任一结构:

for i
   for j
      board[i][j]

我已编辑了您的代码:

#include <iostream>
#include <string>

using namespace std;

void drawBoard(char board[3][4])
{
    for (int i = 0; i < 12; i++)
    {
        if(i%4!=3)
        {
            cout<<" "<<board[i/4][i%4]; // board[0 to 2][0 to 2, 3 skept]
            if(i%4<2)
                cout<<" |";
        }
        else
        {
            if(i/4<2)
                cout<<endl<< "---+---+---";
            cout<<endl; // new line
        }
    }
}

int main()
{
    char board[3][4] = { {'x', 'o', 'x', '\0'}, {'o', 'x', 'x', '\0'}, {'o', 
    'o', 'x', '\0'} };
    drawBoard(board);

    cin.get();
}

进入
board[3][4]
的第一个有效索引是0到2。您使用的数字高达11。您的程序通过访问超出边界的索引来显示未定义的行为。确实,尝试了一下,结果是:
void drawBoard(char board[3][4]){int j=0;for(int i=0;i<9;i++{if((i%3)==0 |(i%3)==1){cout确实试过了,结果是:{code>void drawBoard(char board[3][4]){int j=0;for(int i=0;i<9;i++){if((i%3)==0 | |(i%3)==1){cout@alkambanalkaml,如果
i
计数从0到9,那么为什么
board[3][4]
不是
board[3][3][3]
对于
board[3][4]
,board[j][i%3]
是什么意思?它的意思是
((char*)board)[j*4+i%3]
。注意索引位置。
for i
   ((char*)board)[i]
#include <iostream>
#include <string>

using namespace std;

void drawBoard(char board[3][4])
{
    for (int i = 0; i < 12; i++)
    {
        if(i%4!=3)
        {
            cout<<" "<<board[i/4][i%4]; // board[0 to 2][0 to 2, 3 skept]
            if(i%4<2)
                cout<<" |";
        }
        else
        {
            if(i/4<2)
                cout<<endl<< "---+---+---";
            cout<<endl; // new line
        }
    }
}

int main()
{
    char board[3][4] = { {'x', 'o', 'x', '\0'}, {'o', 'x', 'x', '\0'}, {'o', 
    'o', 'x', '\0'} };
    drawBoard(board);

    cin.get();
}
 x | o | x
---+---+---
 o | x | x
---+---+---
 o | o | x