首页 > 解决方案 > C++ 替换动态二维数组中的值

问题描述

我正在尝试替换“。” 在我的数组中带有'O',但它会将其插入其中而不是取代它的位置。请帮助我不知道我做错了什么。

#include <iostream>
using namespace std;
char** createField(int w, int l)
{
    int obstacles;

    char ** arr = new char * [w];
    for(int i=0; i<w; i++)
    {
        arr[i] = new char[l];
    }
//Initializing the values
    for(int i = 0; i < w; ++i)
    {
        for(int j = 0; j < l; ++j)
        {
            arr[i][j] = 0;
        }
    }

    cout<<"Enter number of obstacles: ";
    cin>>obstacles;

   int x=0;
   int y=0;
        for (int j = 0; j < obstacles; ++j) {
            cout<<"Enter location of obstacles: ";
            cin>>x>>y;
            arr[x][y] ='O';
        }
    for(int i = 0; i < w; ++i)
    {
        for(int j = 0; j < l; ++j)
        {
            if(i==0 || i == w-1){
                cout<< arr[i][j]<< 'W';
            }else if(j==0 || j==l-1){
                cout<< arr[i][j]<< 'W';
            } else
                cout<< arr[i][j]<< '.';

        }
        cout<<"\n";
    }


    return arr;
}
int main() {
    int w;
    int l;

    cout << "Enter the Width: ";
    cin >> w;

    cout << "Enter the length: ";
    cin >> l;
//Pointer returned is stores in p
    char **p = createField(w, l);


//Do not Forget to delete the memory allocated.It can cause a memory leak.
    for (int del = 0; del < w; del++) {
        delete[] p[del];
    }
    delete[]p;
}

这是我的输出示例,我希望用“O”替换“。” 而不是介于两者之间。另外,如果有人可以解释为什么会发生这种情况,那将非常有帮助,谢谢。

输出示例:wOw
所需输出:w.Ow

标签: c++

解决方案


当您设置 arr[i][j] = 0 时,它会将 0 转换为 char,然后再将其分配给 arr[i][j]。0 转换为文字'\0',这意味着一个空字符。稍后当您打印 arr 的内容时,在输出中看不到空字符,这是造成您混淆的根本原因的一部分。希望这能更好地解释正在发生的事情。


推荐阅读