0

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?

Zubatman
  • 1,235
  • 3
  • 17
  • 34

2 Answers2

1

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.

sjsam
  • 21,411
  • 5
  • 55
  • 102
0

Dynamic Memory Allocation is a viable solution to your problem, as sjsam said. The only thing I would like to point out is that the code can look like this:

int i,lin,col;
char **matrix;
matrix=malloc(lin * sizeof(char*));
//check for NULL
for(i=0;i<lin;i++){
    matrix[i]=malloc(col * sizeof(char));
    //again,check for NULL
}

Then again, to free your allocated memory, you do:

for(i=0;i<lin;i++)
    free(matrix[i]);
free(matrix);

Hope that answers your question!

  • 1
    In this case memory allocated is not contiguous, ie it is fragmented. You get slow crappy code that burns.and crashes . – sjsam Apr 20 '16 at 16:11
  • Yes you are right but as the OP mentioned she is a beginner C programmer, I thought a simpler code might help her understand about pointers and the "malloc" function. Thank you for pointing that out though! – D.Christodoulou Apr 20 '16 at 16:14
  • This is not simpler either. – sjsam Apr 20 '16 at 16:14