Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allocate matrix in C

i want to allocate a matrix.

is this the only option:

int** mat = (int**)malloc(rows * sizeof(int*))

for (int index=0;index<row;++index)
{
    mat[index] = (int*)malloc(col * sizeof(int));
}
like image 972
Idan Avatar asked Jan 24 '10 20:01

Idan


People also ask

How are arrays allocated in C?

Allocating array storage in C Calls to malloc commonly use a sizeof expression to specify the size in bytes of the requested storage. To allocate storage for an array, just multiply the size of each array element by the array dimension.

How do you allocate memory in C?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.


2 Answers

Well, you didn't give us a complete implementation. I assume that you meant.

int **mat = (int **)malloc(rows * sizeof(int*));
for(int i = 0; i < rows; i++) mat[i] = (int *)malloc(cols * sizeof(int));

Here's another option:

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

Then, you simulate the matrix using

int offset = i * cols + j;
// now mat[offset] corresponds to m(i, j)

for row-major ordering and

int offset = i + rows * j;
// not mat[offset] corresponds to m(i, j)

for column-major ordering.

One of these two options is actually the preferred way of handling a matrix in C. This is because now the matrix will be stored contiguously in memory and you benefit from locality of reference. Basically, the CPU cache will a lot happier with you.

like image 151
jason Avatar answered Sep 26 '22 11:09

jason


The other answers already covered these, but for completeness, the comp.lang.c FAQ has a relevant entry:

How can I dynamically allocate a multidimensional array?

like image 25
jamesdlin Avatar answered Sep 26 '22 11:09

jamesdlin