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.

5
  • 1
    What is the mentioned error ? Commented Jan 22, 2021 at 11:00
  • The second one should be a=(int **) malloc(c*sizeof (int *));, or preferably a=malloc(c*sizeof(*a));. Commented Jan 22, 2021 at 11:02
  • 1
    Also don't cast the return value of malloc, please. Commented Jan 22, 2021 at 11:03
  • 2
    The asterisks in here int **a; and in here **a = are not the same. Commented Jan 22, 2021 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. Commented Jan 22, 2021 at 11:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.