Friday, June 9, 2017

2d dynamic array with known number of column element

how to make dynamic array with known number of column element
for example for a 3d coordinate.

suppose i need to make 2d dynamic array for a 3d coordinate, because the element of 3d coordinate is x, y, z so the number column is 3.
let's say i need to have
double point[some_number][3];
and that number is suppose unknown until we read the file, lets say ptscount.

one simple way to allocate the dynamic 2d array is as follow. 

double (*point)[3] = (double (*)[3])malloc(sizeof(double) * ptscount*3);

brief explanation
- double (*point)[3]: double variable of  "point" that has 3 array element, this will make point[ptscount][3]

- (double (*)[3]): casting to double of pointer that has 3 array element

- malloc(sizeof(double) * ptscount*3): memory allocation for (the size of double variable) times(×) (ptscount (number or row of the array) with 3 column)

after using it you have to free the memory
free (point);

No comments:

Post a Comment