二维数组不显示正确的输出

时间:2012-04-26 14:37:39

标签: 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

数组未正确显示。

1 个答案:

答案 0 :(得分:1)

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

#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-dimmension的含义。如果你的意思是x水平运行比我认为i和j for-loops呼喊反转,因为x代表列。