0

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.

user1611753
  • 355
  • 1
  • 4
  • 9
  • I am new to programming and trying to learn.. So kindly help – user1611753 Sep 21 '12 at 11:56
  • Start by understanding simple, 1D-arrays, and the relation or non-relation between arrays and pointers... – Kerrek SB Sep 21 '12 at 11:57
  • Here's a link with what you need to know: http://stackoverflow.com/questions/12462615/how-do-i-correctly-set-up-access-and-free-a-multidimensional-array-in-c – Mike Sep 21 '12 at 12:13

1 Answers1

0

This line:

printf("%d",*(p+j));

actually prints the pointer to the row j (because p points to the rows, not row elements). You can fix it by dereferencing once more:

printf("%d",p[i][j]));

and remove

 p += 1;

from the second loop.

Also, your code is quite hard to read, try to avoid ***temp and reassigning pointers every other line.

Karel Petranek
  • 15,005
  • 4
  • 44
  • 68