Idan
Idan

Reputation: 5827

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));
}

Upvotes: 21

Views: 132308

Answers (6)

abhay  jain
abhay jain

Reputation: 156

what you can do is

int (*mat)[col];
mat=(int (*)[col])malloc(sizeof(*mat)*row);

and then use this new matrix as mat[i][j]

Upvotes: 6

Matthew Scharley
Matthew Scharley

Reputation: 132534

You can collapse it to one call to malloc, but if you want to use a 2d array style, you still need the for loop.

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

for (int i = 0; i < rows; i++) {
    matrix[i] = matrix + rows * sizeof(int*) + rows * cols * sizeof(int) * i;
}

Untested, but you get the idea. Otherwise, I'd stick with what Jason suggests.

Upvotes: 0

jamesdlin
jamesdlin

Reputation: 90184

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?

Upvotes: 8

jason
jason

Reputation: 241789

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.

Upvotes: 53

St&#233;phan Kochen
St&#233;phan Kochen

Reputation: 19943

You may also use calloc, which will additionally zero initialize the matrix for you. The signature is slightly different:

int *mat = (int *)calloc(rows * cols, sizeof(int));

Upvotes: 3

Ana Betts
Ana Betts

Reputation: 74702

How about just:

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

Upvotes: 2

Related Questions