Blog Archives

Dynamic Multidimensional Array in C and C++

Here’s how you would declare a one dimensional array in C:

 long* array;
 array = malloc(dimension*sizeof(long));

Equivalent to:
long array[dimension];

For two dimensional array in C, where each element are located in contiguous memory space:

long** array2;
long* tmp;
array2 = (long**)malloc(dimension1 * sizeof(long*));
 tmp = (long*)malloc(dimension1 * dimension2 * sizeof(long));
  for (i = 0;i<dimension1;i++){
	array2[i] = tmp + (i*dimension2);
  }

One dimensional array in C++:

int *array;
array = new int [dimension];

For two dimensional array in C++:

int **array2;
array2 = new int* [dimension1];
for (i=0; i<dimension1; ++i)
   array2[i] = new int[dimension2];

If you get segmentation faults, and you have arrays in your program, most likely it’s because of those pointers. And never try to access a pointer that leads to NULL. Fault!

Advertisements