Dynamic memory allocation of 2d arrays

This tip submitted by nandam on 2006-08-29 06:26:56. It has been viewed 5832 times.
Rating of 3.7 with 3 votes

To dynamicallly alloc an array of size mXn with fewer memory allocations than n + 1:

double **M;
M= (double**)malloc(m*sizeof(double*));
M[0] =(double*)malloc(m*n*sizeof(double));

By avoiding some allocations, this code can run faster than the ususal code:

M= (double**)malloc(m*sizeof(double*));
for(i= 0;i

More tips

Help your fellow programmers! Add a tip!