I have a program based on a matrix and need various functions to be able to access this matrix and it's dimensions, which I get from the user. I've managed to do it by passing them as arguments to each separate function, but that doesn't seem efficient.
When I try to declare this:
int lin, col;
char matrix[lin][col];
I get an error: variable length array declaration not allowed at file scope. I'm guessing it's because at that point, I haven't asked the user for 'lin' and 'col'? My question is: is there a way to make my matrix of variable dimensions have global scope? Or a way to access this matrix and dimensions without passing them as arguments to various functions?
Do
char **matrix;
Read rows r
and columns c
as input from the user.
Then do :
*matrix[c]=malloc(sizeof(matrix[r][c]); //You get contiguous memory here
Then you access the matrix like matrix[x][y] , the same way you access a 2D array.
At the end of the day, clear the memory allocated :
clear(matrix);
Or a way to access this matrix and dimensions without passing them as arguments to various functions?
Well, yes . You usually you pass the arguments like below :
void print_matrix(char** matrix_copy,int rows,int cols)
{
//Access the matrix using matrix_copy[x][y] format
}
You can just pass the matrix from main()
like below :
print_matrix(matrix,r,c); // As simple as that.
Since you don't need arguments you need a workaround which is simple.
Declare
char **matrix;
int r,c; // rows & columns
outside all the functions, so that they are accessible across the program.
In other words declare them in file scope. But in this case make sure that you access the matrix
only after it is allocated some space using malloc
.