Dynamic memory allocation in 2d array

2019-08-03 08:11发布

The scanf statement is giving me trouble. I have tried &arr[i][j] and (arr+i)+j in place of *(arr+i)+j. However, this statement is still giving problems. Here is my code:

int **arr, m, n, i, j;
scanf("%d%d", &m, &n);
arr = (int **) malloc( m * sizeof(int *) );

for (i = 0; i < m; i++)
  arr[m] = (int *) malloc(n*sizeof(int));

for(i = 0; i < m; i++)
  for(j = 0; j < n; j++)
    scanf("%d", *(arr + i) + j); //this statement

for(i = 0; i < m; i++) {
  for(j = 0; j < n; j++) {
    printf("%d ", *(*(arr + i) + j));
  printf("\n");
}

getch();
return 0;

标签: c malloc scanf
1条回答
淡お忘
2楼-- · 2019-08-03 08:17

There is a severe typo:

  arr[m] = (int *) malloc(n*sizeof(int));

Should be

  arr[i] = malloc(n * sizeof(int));
查看更多
登录 后发表回答