由双指针创建的C++ 2d数组

die*_*403 0 c++ arrays pointers

我想用指针和show创建2d数组然后显示它.我按增量指针(一个*)和列索引更改行.我的代码:

int ** tabl=new int *[4];
for (int i=0;i<10;i++)
    tabl[i]=new int [3];
int **ptab=tabl;//save first position of array

for (int i=0;i<4;i++)
{
    for (int j=0;j<3;j++)
    {
        *tabl[j]=rand()%10 +1;
        printf("%4d",*tabl[j]);
    }
    tabl++;
}
tabl=ptab;
cout<<endl<<endl<<endl;
for (int i=0;i<4;i++)
{
    for (int j=0;j<3;j++)
    {
        printf("%4d",*tabl[j]);
    }
    tabl++;
}
Run Code Online (Sandbox Code Playgroud)

输出:

   2   8   5   1  10   5   9   9   3   5   6   6

   2   1   9   1   9   5   9   5   6   5   6   6
Run Code Online (Sandbox Code Playgroud)

但是第二个循环中的一些数字与原始数字不同.为什么?

Ish*_*ael 5

问题是你引用元素的方式.它应该是(*tabl)[j],而不是*tabl[j].

还要注意你在这里去了beyound分配的内存:

int ** tabl=new int *[4];
for (int i=0;i<10;i++)
               ^
    -----------+
Run Code Online (Sandbox Code Playgroud)