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!

Posted on October 24, 2010, in Programming and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: