c++ - 二维数组未显示正确的输出

标签 c++

我希望用户在二维数组中输入值。他还可以选择每个维度的大小

    int main()
{
    int x;
    int y;
    int *p;
    cout<<"How many items do you want to allocate in dimension x?"<<endl;
    cin>>x;
    cout<<"How many items do you want to allocate in dimension y?"<<endl;
    cin>>y;
    p = new int[x,y];
    for(int i=0; i<x; i++)    //This loops on the rows.
    {
        for(int j=0; j<y; j++) //This loops on the columns
        {
            int value;
            cout<<"Enter value: "<<endl;
            cin>>value;
            p[i,j] = value;
        }
    }
    drill1_4 obj;
    obj.CopyArray(p,x,y);

}

然后,通过

输出二维数组
class drill1_4
{
public:
    void CopyArray(int*,int,int);
private:
    int *p;
};

void drill1_4::CopyArray(int* a,int x,int y)
{
    p = a;
    for(int i=0; i<x; i++)    //This loops on the rows.
    {
        for(int j=0; j<y; j++) //This loops on the columns
        {
            cout << p[i,j]  << "  ";
        }
        cout << endl;
    }
    getch();
}

逻辑看起来不错,但是假设,如果用户输入数字,数组应该如下所示

1 2

3 4

但是,它看起来像这样:

3 3

4 4

数组显示不正确。

最佳答案

不知道您是否找到了问题的答案。上面的评论告诉你哪里错了。这是一个可能的答案。

#include <cstdio>

#include <iostream>
using namespace std;

class drill1_4
{
public:
    void CopyArray(int**,int,int);
private:
    int **p;
};

void drill1_4::CopyArray(int** a,int x,int y)
{
    p = a;
    for(int j=0; j<y; ++j)    //This loops on the rows.
    {
        for(int i=0; i<x; ++i) //This loops on the columns
        {
            cout << p[i][j]  << "  ";
        }
        cout << endl;
    }
    cin.get();
}


   int main()
{
    int x;
    int y;
    int **p;
    cout<<"How many items do you want to allocate in dimension x?"<<endl;
    cin>>x;
    cout<<"How many items do you want to allocate in dimension y?"<<endl;
    cin>>y;
    p = new int*[x];
    for (size_t i = 0; i < x; ++i)
        p[i] = new int[y];

    for(int j=0; j<y; ++j)    //This loops on the rows.
    {
        for(int i=0; i<x; ++i) //This loops on the columns
        {
            int value;
            cout<<"Enter value: "<<endl;
            cin>>value;
            p[i][j] = value;
        }
    }
    drill1_4 obj;
    obj.CopyArray(p,x,y);
}

我不确定我是否理解 x 维度的含义。如果你的意思是 x 水平运行,那么我认为 i 和 j for 循环应该颠倒过来,因为 x 将代表列。

关于c++ - 二维数组未显示正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10335685/

相关文章:

c++ - 接口(interface)和公共(public)方法

c++ - 为什么 "class"中有 "template <class x>"?

c++ - Windows7中的硬件加速缩放MFT

C++:为什么我不能创建一个结构队列?

c++ - 如何在 Visual Studio 中查找特定类的重载运算符的所有引用?

c++ - C++中如何使用栈

java - 编程中实例的含义是什么?

C++ - "Stack automatic"是什么意思?

c++ - 使用 map<string,int> 在 switch-case 语句中使用字符串

c++ - 将一系列图像写入缓冲存储器的最佳方法