-4

I have written this program and I want to know if it is correct or not? What will happen in this array pInt?

#include <iostream>
using namespace std;

int main(int argc, char*argv[])
{
    system("color 1f");

    int **pInt=new int*[2];
    int i=0,j=0;
    pInt[0]=new int[4];
    pInt[1]=new int[7];

    for(i=0;i<2;i++)
    {
        for(j=0;j<7;j++)
        {
            pInt[i][j]=i+j;     
        }
    }

    for(i=0;i<2;i++)
        for(j=0;j<7;j++)
            cout<<"pInt["<<i<<"]["<<j<<"]= "<<pInt[i][j]<<endl;

    cout.write("\n\n\n\n\n",5);
    return 0;
}
4

1 回答 1

2

在您的循环中,我添加了一个小条件来检查数组索引。现在程序运行正常。现在就试试!

#include <iostream>
using namespace std;

int main(int argc, char*argv[])
{
    system("color 1f");

    int **pInt=new int*[2];
    int i=0,j=0;
    pInt[0]=new int[4];
    pInt[1]=new int[7];

    for(i=0;i<2;i++)
         for(j=0;j<(i==0?4:7);j++)
            pInt[i][j]=i+j;     

    for(i=0;i<2;i++)
        for(j=0;j<(i==0?4:7);j++)
            cout<<"pInt["<<i<<"]["<<j<<"]= "<<pInt[i][j]<<endl;

    cout.write("\n\n\n\n\n",5);
    return 0;
}
于 2013-09-20T07:37:32.273 回答