gj1103
gj1103

Reputation: 127

Dynamic memory allocation in 2d array

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;

Upvotes: 1

Views: 2396

Answers (1)

timrau
timrau

Reputation: 23058

There is a severe typo:

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

Should be

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

Upvotes: 2

Related Questions