创建一个以运行时维度作为输入的矩阵

Creating a matrix with runtime dimentions as input

我写了两个cod。一个工作,而另一个不会。请解释这段代码的工作原理以及为什么后者不起作用。

工作 -

    #include <stdio.h>
#include <malloc.h>

int main(){
  int m, n, i, j;
  scanf("%d%d",&m,&n);
  int *p;
  p = (int *) malloc(m*n*sizeof(int));
  for(i=0;i<m;i++){
    for(j=0;j<n;j++){
      scanf("%d", (p+i*n+j));
    }
  }
}

不工作 -

#include <stdio.h>
#include <malloc.h>

int main(){
  int m, n, i, j;
  scanf("%d%d",&m,&n);
  int *p;
  p = (int *) malloc(m*n*sizeof(int));
  for(i=0;i<m;i++){
    for(j=0;j<n;j++){
      scanf("%d", p[i][j]);
    }
  }
}

error is - subscripted value is neither array nor pointer nor vector
scanf("%d", p[i][j]);

对于第二个示例,p 需要是指向数组的指针,或者指向指针的指针。

可能是这样的

int **p = malloc(m * sizeof(int *));
for (size_t i = 0; i < m; ++i)
{
    p[i] = malloc(n * sizeof(int));
    for (size_t j = 0; j < n; ++j)
    {
        scanf("%d", &p[i][j]);
    }
}