2

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;
0

1 Answer 1

3

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].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.