Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is it valid in C to dynamically allocate 2d arrays this way?

//fixed size
int (*arr2d)[9][9]=malloc(sizeof(int[9][9]));

//variable size
int x=5,y=3;
int (*arr2d)[x][y]=malloc(sizeof(int[x][y]));

//assignment
(*arr2d)[0][1]=2;

EDIT: By "valid" I mean, are there any pitfalls as opposed to:

int i,x=5,y=10;
int **arr2d=malloc(sizeof(int*[x]));
for(i=0;i < x;i++)
    arr2d[i]=malloc(sizeof(int[y]));

arr2d[0][0]=5;
share|improve this question

1 Answer 1

up vote 2 down vote accepted

The only real issue is if you request more memory than the malloc call can satisfy (you may have enough memory available, but not in a single, contiguous block).

To save your sanity, do something like this instead:

T (*arr)[cols] = malloc( sizeof *arr * rows );

This will allow you to index it as arr[i][j] instead of (*arr)[i][j].

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.