Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected output for simple 2d array in c

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
   }

>Solution :

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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading