简体   繁体   English

如何使用指针消除二维数组声明中的错误?

[英]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.任何帮助将不胜感激。

You declared a pointer of the type int ** that is not initialized and has an indeterminate value.您声明了一个未初始化且具有不确定值的int **类型的指针。

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 ** .表达式**a具有int类型,而右侧表达式具有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请注意,如果在第一个程序中,变量r表示行,变量c表示列,那么您应该按行分配 arrays,程序应该看起来像

#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.否则,表达式a[i]将产生一列而不是一行。

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.如上所示分配 arrays 后,表达式**a等效于表达式a[0][0]并将产生存储在第一行第一列中的int类型的 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM