【问题标题】:How to remove error in 2-d array declaration using pointers?如何使用指针消除二维数组声明中的错误?
【发布时间】:2021-04-26 20:09:02
【问题描述】:

如果我将二维数组声明为

#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));
    }
}

上述程序运行成功。

#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));
    }
}

但是编译器在上面的程序中显示错误。

为什么会这样?任何帮助将不胜感激。

【问题讨论】:

  • 提到的错误是什么?
  • 第二个应该是a=(int **) malloc(c*sizeof (int *));,或者最好是a=malloc(c*sizeof(*a));
  • 这里int **a;和这里**a =的星号不一样。
  • 分解原来的int **a = (int **)malloc(c * sizeof(int *));int **a = ...声明a的类型为int **... a=(int **)malloc(...);初始化a

标签: arrays c pointers dynamic-memory-allocation dereference


【解决方案1】:

您声明了一个 int ** 类型的指针,该指针未初始化且具有不确定值。

int **a;

然后在下一个语句中,您将取消引用指针两次

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

表达式**a 的类型为int,而右侧表达式的类型为int **

因此编译器会发出一条消息,指出操作数具有不同的类型。

此外,如果要运行这样的程序,取消引用未初始化的指针会导致未定义的行为。

你至少应该写

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

请注意,如果在第一个程序中变量r 表示行,变量c 表示列,那么您应该按行分配数组,程序应该是这样的

#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));
    }
}

否则表达式a[i] 将产生一列而不是一行。

如上所示分配数组后,表达式**a 等效于表达式a[0][0],并将生成int 类型的对象,该对象存储在第一行的第一列中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多