2

If I declare a two dimensional array as

#include <stdio.h>
#include <stdlib.h>
int main() { int c=5;int r=6;
    int **a=(int **) malloc (c*sizeof(int *));
    int i,j;
    for (i=0;i<c;i++){
        *(a+i)=(int *) malloc (r*sizeof (int));
    }
}

The above program works successfully.

#include <stdio.h>
#include <stdlib.h>
int main() { int c=5;int r=6;
    int **a;
     **a=(int **) malloc (c*sizeof (int *));
    int i,j;
    for (i=0;i<c;i++){
        *(a+i)=(int *) malloc (r*sizeof (int));
    }
}

But the compiler shows an error in the above program.

Why so? Any help would be greatly appreciated.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Girik Garg
  • 87
  • 7
  • 1
    What is the mentioned error ? – GabrielT Jan 22 '21 at 11:00
  • The second one should be `a=(int **) malloc(c*sizeof (int *));`, or preferably `a=malloc(c*sizeof(*a));`. – Ian Abbott Jan 22 '21 at 11:02
  • 1
    Also [don't cast the return value of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc), please. – costaparas Jan 22 '21 at 11:03
  • 2
    The asterisks in here `int **a;` and in here `**a =` are not the same. – alk Jan 22 '21 at 11:07
  • To break down the original `int **a = (int **)malloc(c * sizeof(int *));`, `int **a = ...` declares the type of `a` to be `int **` and `... a=(int **)malloc(...);` initializes `a`. – Ian Abbott Jan 22 '21 at 11:07

1 Answers1

3

You declared a pointer of the type int ** that is not initialized and has an indeterminate value.

int **a;

Then in the next statement you are dereferencing the pointer two times

 **a=(int **) malloc (c*sizeof (int *));

The expression **a has the type int while the right hand side expression has the type int **.

So the compiler issues a message that the operands have different types.

Moreover dereferencing an uninitialized pointer results in undefined behavior if such a program will be run.

You should at least write

 a=(int **) malloc (c*sizeof (int *));

Pay attention to that if in the first program the variable r means rows and the variable c means columns then you should allocate arrays by rows that is the program should look like

#include <stdio.h>
#include <stdlib.h>
int main() { int c=5;int r=6;
    int **a=(int **) malloc (r*sizeof(int *));
    int i;
    for (i=0;i<r;i++){
        *(a+i)=(int *) malloc (c*sizeof (int));
    }
}

Otherwise the expression a[i] will yield a column instead of a row.

After you will allocate arrays as shown above then the expression **a is equivalent to the expression a[0][0] and will yield the object of the type int that is stored in the first column of the first row.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335