Hi Mike,
The ultimate answer to this question is through benchmarking.
See what are your objectives (performance, or space or what)
There are various approach to create a matrix in C, namely:
multiple malloc() calls
single malloc() call with pointer arithmetic
simulate using 1D array.
I suggest a benchmarking by creating once, and index the array a lot of
times and measure the mean allocation time, mean access time, and mean free
time.
Andrew
Mike Tyka said:
Amit said:
kaul said:
i want to create a 2-d array containg r rows and c columns by dynamic
memory allocation in a single statement so that i will be able to access
the ith and jth index as say arr[j]
how is that possible?
try this:
int nrows,ncols;
int **array;
array = malloc(nrows * sizeof(int *));
for (i=0;i<nrows;i++)
array=malloc(ncols * sizeof(int));
I never though about doing it this way, i always allocate a linear array of
row*columns elements and
access them using a little macro:
#define sqrmat(y,x,width) ((y)*(width) + (x))
random access then looks like array[sqrmat(myRow,myColumn,nColumns)]
I wonder if anyone has any views on how the two approches compare in terms
of performance ?
In the above method, i assume C must do an internal multiplication of the
sort i'm implementing
explicitly ?
Mike