0

ユーザーに2次元配列に値を入力してもらいたい。彼はまた、各次元のサイズを選択することができます

    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);

}

次に、次の方法で2次元配列を出力します。

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-dimmensionの意味がよくわかりません。xが水平方向に実行されることを意味する場合、xは列を表すため、iとjのforループは逆になります。

于 2012-04-26T21:40:26.110 に答える