I am trying to implement a 2D array using a double pointer. How I am trying to implement is visualsing it as per its physical representation. For example, consider a 2 x 2 matrix and its physical representation is
c1 c2
R1 -> A00 A01
R2 -> A10 A11
Step 1: Creating a double pointer to point to the first row
Step 2: creating the first level pointer to point to the address of c1
Step 3: Input from user
Step 4: Creating the first level pointer to point to the address of c2
step 5: Input from user
Step 6: Increment the Row pointer to point R2
Step 7: Repeat from steps 2 to 5
Below is the code snippet of the code implemented by me:
int _tmain(int argc, _TCHAR* argv[])
{
int **p,***temp;
p = (int **)malloc(nRows*sizeof(int *));
//Allocating memory for two rows, now p points to R1
temp = &p; //storing the address of p to restore it after storing the values
for(int i=0;i<nRows;i++)
{
for(int j=0;j<nCols;j++)
{
*(p+j) = (int *)malloc(sizeof(int));
//Allocating memory for col , now *p points to C1
scanf("%d",*(p+j));
}
p += 1; // NOw p is pointing to R2
}
p = *temp; // restoring the base address in p;
for(int i=0;i<nRows;i++)
{
for(int j=0;j<nCols;j++)
printf("%d",*(p+j));
// In first iteration print values in R1 and R2 in second iteration
p += 1; // points to the next row
}
getch();
return 0;
}
The scanf seems to work fine. But in the printf I get erratic results. It starts pointing to some other location
Can you please let me know how to implement this 2D array in the way I have said before? I am doing this exercise for experimental purpose just to get an in-depth knowledge about the working of double pointers.