【问题标题】:C++ replacing values in a dynamic 2D ArrayC++ 替换动态二维数组中的值
【发布时间】:2019-12-07 07:32:41
【问题描述】:

我正在尝试替换 '.'在我的数组中带有'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' 替换 '.'而不是介于两者之间。另外,如果有人可以解释为什么会发生这种情况,那将非常有帮助,谢谢。

输出示例:w.O.w
期望的输出:w.Ow

【问题讨论】:

  • 首先,我有一个问题:您认为cout&lt;&lt; arr[i][j]&lt;&lt; '.' 将发送多少个字符到标准输出?或者cout&lt;&lt; arr[i][j]&lt;&lt; 'W' 怎么样?
  • 它假设是用户输入的值,所以如果用户输入 10 的宽度和 11 的长度,数组将相应地自行调整。
  • 我不是在问有多少循环迭代;我只是在询问这两个陈述。 就是这样。是 1 吗? 2 ? 3 ?
  • 我很确定只有 1。我对编程还是很陌生,如果不准确,请见谅。
  • 这是两个。 (抱歉,正在与嘉宾 Gordon Ramsey 一起观看 Hot Ones 剧集。天哪,那是 FaF。)。这意味着每次执行cout&lt;&lt; arr[i][j]&lt;&lt; 'W'cout&lt;&lt; arr[i][j]&lt;&lt; '.' 时,都会打印两个 字符:a[i][j] 中的内容,以及尾随字符W.。把它写在纸上,看看它现在是否有意义,你得到的输出。

标签: c++


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-04
    • 2011-01-11
    • 2018-10-15
    • 2021-09-20
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    相关资源
    最近更新 更多