开发者

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 dy开发者_如何学Gonamically 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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜