Qosmo
Qosmo

Reputation: 1202

Matrix: Memory allocation question

I'm doing a program that reads from a text file in order to determine the size of the matrix (rows and cols) and respective content of the matrix.

I was wondering if something like:

int main()
{
int rows = FunctionThatReadsRows();
int cols = FunctionThatReadsCols();
int matrx[rows][cols];
return 0;
}

Would work? Or does it need to be dynamically allocated? I'm not sure if variables are initialized before any code runs? I need to work with the matrix throughout the program.

And if it does need to be dynamically allocated how should I do it? Thanks.

Upvotes: 1

Views: 213

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

Before C99, you could not declare dynamically-sized arrays (although plenty of compilers support it). In C99, you can.

If you don't want to do this, you'll have to malloc memory on the heap, e.g.:

int *matrix = malloc(sizeof(int) * rows * cols);

However, you won't be able to index into this in a two-dimensional way; you'll need to do something like matrix[i*cols+j] (or write a function/macro to hide this).

Remember to call free(matrix) when you're done with it!

Upvotes: 5

Related Questions