1

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

4
  • How can we help when you don't show the function int **tohan = makeIntArray2D(3, numDisks);? What does it do? Commented Oct 31, 2022 at 16:34
  • Ill Add it in. Thanks for the suggestions Commented Oct 31, 2022 at 16:36
  • 3
    are width and height reversed? Commented Oct 31, 2022 at 16:39
  • That seems to have done it thanks for the suggestion! Commented Oct 31, 2022 at 16:40

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I will be sure to include that code if a question along thes lines comes up
That's all we ask — that you learn for the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.