0
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
    int **a;
    int i,j,p;

    a=(int**)malloc(3*sizeof(int*));
    for(i=0;i<3;i++)
    {
        *(a+i)=(int*)malloc(2*sizeof(int));
    }
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",(*(a+i)+j));
        }
        for(i=0;i<3;i++)
        {
            for(j=0;j<2;j++)
            {
                p=*(*(a+i)+j);
                printf("%d ",p);
            }
        }
    }
}

In this code i am dynamically allocating memory to my matrix using pointers... but i am able to enter value only to the first row and the rest the address of the pointer is being printed as seen below..

Only the first row elements are taken in and output of the first row is given but the second row onwards no input is taken but garbage value is printed. help me figure out the error. Please help me figure out the mistake in this code.

Haris
  • 12,120
  • 6
  • 43
  • 70
yogs
  • 43
  • 6

2 Answers2

0

The 2 loops that you are using to print, should be outside the other for loop that you are using to read the inputs.

Like

for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        scanf("%d",(*(a+i)+j));
    }
}
for(i=0;i<3;i++)
{
    for(j=0;j<2;j++)
    {
        p=*(*(a+i)+j);
        printf("%d ",p);
    }
}

Plus, according to your program, it seems that the matrix that you are using is a 3*3 matrix (that means 9 integers), however you are allocating only memory for 2 int inside the for loop

*(a+i)=(int*)malloc(2*sizeof(int));

Try allocating memory for 3 integers, it should work

*(a+i)=(int*)malloc(3*sizeof(int));

Few more things

1) You don't need another variable p if you are just printing the value.

printf("%d ",*(*(a+i)+j));

2) You don't need to type cast the return of malloc(), see this.

Community
  • 1
  • 1
Haris
  • 12,120
  • 6
  • 43
  • 70
0

You should correct your code as below:

    for(i=0;i<3;i++)
{
    for(j=0;j<2;j++)
    {
        scanf("%d",(*(a+i)+j));
    }
}

for(i=0;i<3;i++)
{
    for(j=0;j<2;j++)
    {
        p=*(*(a+i)+j);
        printf("%d ",p);
    }
}

Firstly, the code shloud be:

for(j=0; j<2; j++)
    scanf("%d", (*(a+i)+j));

Secondly, the for loop should put outside.

cwfighter
  • 502
  • 1
  • 5
  • 20