Anish T Moncy
Anish T Moncy

Reputation: 11

Program using dynamic memory allocation

I have the below program in C. How did p[0][0] become 1? Can somebody help in understanding?

#include <stdio.h>
#include<stdlib.h>

main()
{
  int i,j;
int **p=(int **)malloc(2 * sizeof(int *));
  p[0]=(int*) malloc(2*sizeof(int));
  p[1]=p[0];
  for(i=0;i<2;i++)
    for(j=0;j<2;j++)
     {
            p[i][j]=i+j;
            printf("%d,%d,%d",i,j,p[i][j]);
            printf("\n");
     }
 printf("%d,%d,%d",i,j,p[0][0]);
}

the output is as below

0,0,0
0,1,1
1,0,1
1,1,2
2,2,1

Upvotes: 0

Views: 64

Answers (2)

John Bode
John Bode

Reputation: 123578

After the following lines of code:

int **p=(int **)malloc(2 * sizeof(int *));
p[0]=(int*) malloc(2*sizeof(int));
p[1]=p[0];

this is what you have in memory:

   int **        int *           int
   +---+         +---+           +---+
p: |   | ------> |   | p[0] -+-> |   | p[0][0], p[1][0]
   +---+         +---+       |   +---+
                 |   | p[1] -+   |   | p[0][1], p[1][1]
                 +---+           +---+

p[0] and p[1] point to the same 2-element array, so anything you write to p[0][i] is reflected in p[1][i] and vice-versa.

What you probably meant to do was something like

int **p = malloc( 2 * sizeof *p ); // cast not necessary, sizeof *p == sizeof (int *)
p[0] = malloc( 2 * sizeof *p[0] );
p[1] = malloc( 2 * sizeof *p[1] );

which would give you

   int **        int *            int 
   +---+         +---+            +---+
p: |   | ------> |   | p[0] ----> |   | p[0][0]
   +---+         +---+            +---+
                 |   | p[1] --+   |   | p[0][1]
                 +---+        |   +---+
                              |
                              |   +---+ 
                              +-> |   | p[1][0]
                                  +---+
                                  |   | p[1][1]
                                  +---+

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

The same pointer is assigned to p[0] and p[1]. This means p[0] and p[1] points at the same array. Therefore updates done via p[1] is also visible via p[0].

In the second iteration of outer for loop, 1 is assigned to p[1][0]. This makes p[0][0] to be 1.

Upvotes: 3

Related Questions