Reputation: 153
I want to create 2d array using pointer and show then show it. I change rows by increment pointer (one *) and columns by index. My code:
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++;
}
Output:
2 8 5 1 10 5 9 9 3 5 6 6
2 1 9 1 9 5 9 5 6 5 6 6
But some of the digits in the second loop are different then the original. Why?
Upvotes: 0
Views: 67
Reputation: 12795
The problem is the way you refer to the element. It should be (*tabl)[j]
, not *tabl[j]
.
Also note that you go beyound allocated memory here:
int ** tabl=new int *[4];
for (int i=0;i<10;i++)
^
-----------+
Upvotes: 5