0

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

    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

数组未正确显示。

4

1 回答 1

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 维度是什么意思。如果您的意思是 x 水平运行,那么我认为 i 和 j for-loops 会颠倒,因为 x 将代表列。

于 2012-04-26T21:40:26.110 回答