Dynamic memory allocation in 2d array

2019-08-03 07:56发布

问题:

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;

回答1:

There is a severe typo:

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

Should be

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


标签: c malloc scanf