How to remove error in 2-d array declaration using pointers?

Viewed 38

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.

1 Answers

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.

Related