1

I am trying to make a 2D dynamic array that calculates the derteminant of 4 or 9 numbers.

While using pointers and a dynamic array worked flawlessly in a 1D array, I can't wrap my head around what I have to do to make it owrk in 2D. So far, the program compiles properly and receives input. However, it does not print anything. I even tried printing a single cell content. Nothing.

Here is the code:

  #include <stdio.h>
    #include <stdlib.h>
    
    int size; int i; int j; int **arDet; int a; int b; int c; int d; int e; int f; int g; int h;
    
    int input()
    {
        do
        {
            scanf("%d", &size);
        }while(size > 3 || size < 2);
        arDet = (int**)malloc(sizeof(int)*size);
        for(i = 0 ; i < size; i++)
        {
            for(j = 0 ; j < size; j++)
            {
                scanf("%d", &arDet[i][j]);
            }
        }
    }
    
    int main()
    {
        input();
        if(size == 2)
        {
            printf("%d\n", arDet[0][0]*arDet[1][1] - arDet[0][1]*arDet[1][0]); 
            return 0;
        }else if(size == 3)
        {
           // printf("%d", arDet[0]*(arDet[4]*arDet[8] - arDet[7]*arDet[5]) - arDet[1]*(arDet[3]*arDet[8] - arDet[5]*arDet[6]) + arDet[2]*(arDet[3]*arDet[7] - arDet[6]*arDet[4]));
            return 0;
        }else
        {
            return -1;
        }
    }

1 Answer 1

1
  • You only allocated an array to store pointers to each rows. You have to allocate arrays to store values for each rows.
  • The size calculation for arDet is wrong. The elements of arDet are int*. int (4 bytes for example) has shorter size than int* (8 bytes for example) in some environments and your code will cause trouble in such environments.
  • Casting results of malloc() in C is discouraged.
    arDet = malloc(sizeof(arDet[0])*size); /* fix size calculation */
    for(i = 0 ; i < size; i++)
    {
        arDet[i] = malloc(sizeof(arDet[i][0]) * size); /* add this */
        for(j = 0 ; j < size; j++)
        {
            scanf("%d", &arDet[i][j]);
        }
    }

Also note that the commented line

       // printf("%d", arDet[0]*(arDet[4]*arDet[8] - arDet[7]*arDet[5]) - arDet[1]*(arDet[3]*arDet[8] - arDet[5]*arDet[6]) + arDet[2]*(arDet[3]*arDet[7] - arDet[6]*arDet[4]));

doesn't make sense because C doesn't support multiplying two pointers and indice above 2 is out-of-range when size is 3.

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

1 Comment

Yes, that was exactly the issue. I am completely new with C and I can't wrap my head around pointers, but your solution makes perfect sense.

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.