0

Basically, I have written a program to calculate the determinant of a matrix.

However, this feels like quite static yet (i.e. the dimension is passed as an argument). Is there any way to make it more dynamic (without vectors) with something like pointers?

#include <bits/stdc++.h> 
using namespace std; 

#define N 4 

void getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n) 
{ 
    int i = 0, j = 0; 

    for (int row = 0; row < n; row++) 
    { 
        for (int col = 0; col < n; col++) 
        { 
            if (row != p && col != q) 
            { 
                temp[i][j++] = mat[row][col]; 
  
                if (j == n - 1) 
                { 
                    j = 0; 
                    i++; 
                } 
            } 
        } 
    } 
} 
  
int determinantOfMatrix(int mat[N][N], int n) 
{ 
    int D = 0;
  
    if (n == 1) 
        return mat[0][0]; 
  
    int temp[N][N];  
    int sign = 1; 
  
    for (int f = 0; f < n; f++) 
    { 
        getCofactor(mat, temp, 0, f, n); 
        D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); 
  
        sign = -sign; 
    } 
  
    return D; 
} 
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
VIVID
  • 555
  • 6
  • 14
  • 1
    Short answer - no. You can't get an array's size from a raw pointer to the array, so you have to either pass in the size as a parameter, or use a container like `std::array` or `std::vector` that carries its own size. – Remy Lebeau Sep 09 '20 at 19:35
  • 1
    [`#include `](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) Don't do that please! – πάντα ῥεῖ Sep 09 '20 at 19:41
  • 1
    array, dynamic size, with something like pointers, that is `std::vector`. Why don't you want to use it? – 463035818_is_not_an_ai Sep 09 '20 at 20:02
  • @idclev463035818 I'm learning C++ now, so I don't know all the properties of `std::vector` yet – VIVID Sep 10 '20 at 03:36
  • c-arrays are super complicated, vectors are simple. Getting accustomed to c-arrays has some value, but being new to C++ is no reason to prefer them over vectors – 463035818_is_not_an_ai Sep 10 '20 at 08:18
  • @idclev463035818 thank you for the response. I will start learning vectors ASAP :) – VIVID Sep 10 '20 at 08:42

1 Answers1

0

There is no way to pass a pointer to an array of dynamic size. And the inner dimensions of an array cannot be dynamic anyway.

What you can do instead is use a one dimensional dynamic array, pass pointer to element of that array as usual, and store the rows one after the other, and calculate the index based on the row size passed as an array. This results in the same layout as an array of arrays would have, but the "virtual" dimensions can be dynamic.

eerorika
  • 232,697
  • 12
  • 197
  • 326