views:

50

answers:

1

Hello! 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.

+4  A: 

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!

Oli Charlesworth
Thanks!! I'll accept ASAP.
Queops
It's worth pointing out that if your matrix is large, you'll want to malloc it anyway. Dynamically sized arrays in C99 go on the stack and you don't want to blow that up.
Nathon