Home > Back-end >  Unexpected output for simple 2d array in c
Unexpected output for simple 2d array in c

Time:11-01

This is the initialising part of a program im writing. I am new ish to c and am quite confused with one of the outputs I am getting. Any advice would be greatly appreciated

for input 9 11 I get

1 2 3 4 5 6 7 8 9
9 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

when I expect to get

1 2 3 4 5 6 7 8 9
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
void *safeMalloc(int n) {
  void *p = malloc(n);
  if (p == NULL) {
    printf("Error: malloc(%d) failed. Out of memory?\n", n);
    exit(EXIT_FAILURE);
  }
  return p;
}

int **makeIntArray2D(int width, int height) {
  int **arr = safeMalloc(height*sizeof(int *));
  for (int row=0; row < height; row  ) {
    arr[row] = safeMalloc(width*sizeof(int));
  }
  return arr;
}

int main(int argc, char *argv[]) {
        int numDisks;
        int numMoves;
        scanf("%d %d", &numDisks, &numMoves);
        int **tohan = makeIntArray2D(3, numDisks);
        for(int i = 0; i < 3; i  ) {
           for(int j =0; j < numDisks; j  ) {
             tohan[i][j] = 0;
           }
         }
        for(int i = 0; i < 3; i  ) {
          for(int j = 0; j < numDisks; j  ) {
            printf("%d ", tohan[i][j]);
          }
          printf("\n");
        }
        printf("\n");
        for(int k = 0; k < numDisks; k  ) {
          tohan[0][k] = k 1;
        }
        for(int i = 0; i < 3; i  ) {
          for(int j = 0; j < numDisks; j  ) {
            printf("%d ", tohan[i][j]);
          }
          printf("\n");
        }
      printf("\n");
   }

CodePudding user response:

You have:

int **makeIntArray2D(int width, int height) { … }

You call:

int **tohan = makeIntArray2D(3, numDisks);

You expect the height of the array to be 3 and the width 9, but you are passing the parameters in the wrong sequence for the function.

Note: this diagnosis could not be made without seeing the code for makeIntArray2D().

  •  Tags:  
  • c
  • Related