I started to learn C
and started a new argument: the matrices
.
I saw that you can define a matrix in two different ways
WAY 1
The first way using the subscript operator[]
const int N = 3, M = 4;
int matrix[N][M];
but as this it is difficlt to pass the arguments in the functions becouse the
the compiler has to know the matrix number of columns when it compiles the program. so you have to do a function that works only for matrices with n
columns
int my_func( int matrix[][3], const int num_lines){...}
WAY 2
The second way: use an array of arrays
const int N = 3, M = 4;
int** m = (int**) calloc(N, sizeof(int*))
for (int i = 0; i < N; i++){
m[i] = (int*) calloc(M, sizeof(int))
}
So doing so you can easily pass the matrix pointer to a function an work fluently with it but the only problem is the efficency in the memory allocation and the the recall of values.
WAY 3?
Actually i thought that there can be a third way and i was wondering if it was correct doing this
const int N = 3, M = 4;
int array[N*M];
for (int i=0; i<N; i++){
for (int j = 0; j<M; j++){
printf("%d%d: %d\n", i, j, array[ i * M + j ]);
}
}
Doing so by my point of view should be as efficency as the first way that i wrote but u can work with it more fluently in the functions becouse you need only to pass the lines and the columns as arguments
int my_func( const int* matrix, const int num_lines, const int num_columns){...}
Is the way 3
right?