Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65843791/how-to-remove-error-in-2-d-array-declaration-using-pointers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...