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?
*tabl[j]meanstabl[j][0]. You actually wantedtabl[0][j]. It would be better to usetabl[i][j]instead, and not dotabl++, and not haveptab.tabl[i], actuallytabldecays to a pointer, and the code is defined as being equivalent to*(tabl+i).