# Understanding Dynamic Multidimensional Arrays

• (2 Pages)
• 1
• 2

## 21 Replies - 7108 Views - Last Post: 05 August 2012 - 12:44 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=287951&amp;s=0ebf0eb30204561227cdfe203ed86376&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 DevonZ

Reputation: 6
• Posts: 73
• Joined: 04-August 12

# Understanding Dynamic Multidimensional Arrays

Posted 04 August 2012 - 10:55 PM

Hello,

I have an assignment I'm working on which involves creating a PPM image file. I understand how to do the project and it'd take me about 10 minutes to do in PHP. However, I'm new to C++ and I'm trying to understand arrays; more specifically, dynamic multidimensional arrays.

I've created a separate project to experiment with arrays and I was wondering if someone could look through my code and tell me what I've done wrong... When I try to run the following code, the console window crashes.

```#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int res[2] = { 5, 5 };
int ***a;
**a = new int[res[0]];  // Columns
for (int i = 0; i < res[0]; i++) {
*a[i] = new int[res[1]];    // Rows
for (int j = 0; j < res[1]; j++) {
a[i][j] = new int[3];    // Cell Array
a[i][j][0] = i;
a[i][j][1] = j;
a[i][j][2] = 3;
}
}

for ( int i = 0; i < res[0]; i++ )
{
for ( int j = 0; i < res[1]; i++ )
{
cout << "[ ";
for ( int k = 0; k < 3; k++ )
{
cout << a[i][j][k];
if ( k < 2 )
cout << ", ";
}
cout << " ]\n";
}
}

system("PAUSE");
return EXIT_SUCCESS;
}
```

Basically, I am trying to figure out how to create an array with a structure similar to:

Array
- Column 1
- - Row 1
- - - Red
- - - Green
- - - Blue
- - Row 2
- - - Red
- - - Green
- - - Blue
- Column 2
- - Row 1
- - - Red
- - - Green
- - - Blue
- - Row 2
- - - Red
- - - Green
- - - Blue

You get the idea... array[0 to MAX_COLUMNS-1][0 to MAX_ROWS-1][0 to 2]

Thanks!

PS: I'm assuming my problem is with my scarce understanding of pointers, but I'm trying to learn! Please be try to be as specific and detailed as possible in your response! Code examples to demonstrate what you're trying to explain are very helpful as I'm a very visual learner.

Is This A Good Question/Topic? 0

## Replies To: Understanding Dynamic Multidimensional Arrays

### #2 Skydiver

• Code herder

Reputation: 5898
• Posts: 20,138
• Joined: 05-May 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 04 August 2012 - 11:21 PM

On line 10, you are trying to dereference the pointer a before you've initialized it.

### #3 DevonZ

Reputation: 6
• Posts: 73
• Joined: 04-August 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 12:34 AM

Skydiver,

What would I initialize it to? I tried making it NULL or 0. However, I still crash when it reaches Line 11.

Thanks

### #4 Skydiver

• Code herder

Reputation: 5898
• Posts: 20,138
• Joined: 05-May 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 01:44 AM

Probably, you are not quite realizing what is happening with the * operator. When you have a pointer like int * x;, and you write *x = 25;, the means store 25 te wherever x is pointing.

When you have int ***a = NULL; and you wrote **a = new int[res[0]];, you are saying:
```*
*
a
=
new int[res[0]];

```

On line 5, allocate an array of 5 integers, and return a pointer.
On line 3, return 0 as address (since a was initialized to NULL)
On line 2, read the memory at the address from line 3, return the value found there.
On line 1, treat the value from line 2 as an address and read the memory, return the value found there.
On line 4, store the pointer we got from line 5 into the address we got got back from from line 1.

The code goes boom just trying to run line 2 because dereferencing a NULL pointer tends to have that effect.

You will have to initialize a with:
```a = new int **[number_of_rows];

```

This will give an array of pointers to points to int.

This post has been edited by Skydiver: 05 August 2012 - 01:45 AM

### #5 DevonZ

Reputation: 6
• Posts: 73
• Joined: 04-August 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 03:01 AM

Skydiver,

```int ***[num_rows]
```
is doing? I'm beginning to understand pointers better but that line has be baffled.

Furthermore, I've modified but now I'm receiving an error on Line 17 and it's crashing the console window.

```#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
cout << "Past Initialization" << "\n";
int res[2] = { 5, 5 };
int ***a = new int **[res[0]]; // Columns
cout << "Past Defreferencing" << "\n";
for (int i = 0; i < res[0]; i++) {
cout << "Looping Columns: " << i << "\n";
*a[i] = new int[res[1]];    // Rows
for (int j = 0; j < res[1]; j++) {
cout << "Looping Rows: " << i << ":" << j << "\n";
a[i][j] = new int[3];    // Cell Array
cout << "Cell Initalized\n";
a[i][j][0] = i;
a[i][j][1] = j;
a[i][j][2] = 3;
}
}

cout << "\n\n== Now Let's View The Results ==\n\n\n";

for ( int i = 0; i < res[0]; i++ )
{
for ( int j = 0; i < res[1]; i++ )
{
cout << "[ ";
for ( int k = 0; k < 2; k++ )
{
cout << a[i][j][k];
if ( k < 2 )
cout << ", ";
}
cout << " ]\n";
}
}

system("PAUSE");
return EXIT_SUCCESS;
}

```

Thanks again!

### #6 Skydiver

• Code herder

Reputation: 5898
• Posts: 20,138
• Joined: 05-May 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 03:26 AM

DevonZ, on 05 August 2012 - 03:01 AM, said:

```int ***[num_rows]
```
is doing? I'm beginning to understand pointers better but that line has be baffled.

Actually you probably meant:
```new int **[num_rows]

```

This allocates num_rows pointers to pointers to int. (Read it right to left).

DevonZ, on 05 August 2012 - 03:01 AM, said:

Furthermore, I've modified but now I'm receiving an error on Line 17 and it's crashing the console window.

Spoiler

Thanks again!

It's because on line 12, you should have done a[i] = new int*[num_cols];.

I think your confusion is stemming from you jumping right away to 3 dimensions, without mastering 1 or 2 dimensions first.

```// Parallel to int arr[5];
// Array of int's
int *one = new int[5];

// Parallel to int *arr[5];
// Array of pointers to int
int **two = new int*[5];

// Notice that this is a jagged array.
// It need not be square or rectangular.
two[0] = new int[5];
two[1] = new int[2];
two[2] = new int[7];
two[3] = new int[42];
two[4] = new int[13];

```

I'm making a hash of this explanation because it's way past my bed time. Perhaps this will help better: http://www.cplusplus...utorial/arrays/

This post has been edited by Skydiver: 05 August 2012 - 03:30 AM

### #7 DevonZ

Reputation: 6
• Posts: 73
• Joined: 04-August 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 03:37 AM

Skydiver,

With your words and other examples I've found online, I've managed to figure it out and I do believe I have a fair understanding on what's going on now!

For anyone else who may find this thread, here is what I ended up with. (I've also changed the iterator variable names to something meaningful, which can really help visualize the array as a table and prevents getting lost in the code.)

```#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int red = 0, green = 1, blue = 2;
int res[2] = { 5, 5 };
int ***a = NULL;

a = new int **[res[1]]; // Rows
for (int row = 0; row < res[1]; row++)
{
a[row] = new int*[res[0]]; // Cols
for (int col = 0; col < res[0]; col++) {
a[row][col] = new int [3];    // Cell Array
a[row][col][red] = row;
a[row][col][green] = col;
a[row][col][blue] = 3;
}
}

cout << "\n\n== Now Let's View The Results ==\n\n\n";

for ( int row = 0; row < res[0]; row++ )
{
for ( int col = 0; col < res[1]; col++ )
{
cout << "[ ";
for ( int color = 0; color < 3; color++ )
{
cout << a[row][col][color];
if ( color < 2 )
cout << ",";
}
}

cout << " ]\n";
}

system("PAUSE");
return EXIT_SUCCESS;
}

```

Thanks again, Skydiver!

Apparently, I cannot edit my posts...

Here is an update to correct a typo in the output/display of the results...

```#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int red = 0, green = 1, blue = 2;
int res[2] = { 5, 5 };
int ***a = NULL;

a = new int **[res[1]]; // Rows
for (int row = 0; row < res[1]; row++)
{
a[row] = new int*[res[0]]; // Cols
for (int col = 0; col < res[0]; col++) {
a[row][col] = new int [3];    // Cell Array
a[row][col][red] = row;
a[row][col][green] = col;
a[row][col][blue] = 3;
}
}

cout << "\n\n== Now Let's View The Results ==\n\n\n";

for ( int row = 0; row < res[0]; row++ )
{
for ( int col = 0; col < res[1]; col++ )
{
cout << "[ ";
for ( int color = 0; color < 3; color++ )
{
cout << a[row][col][color];
if ( color < 2 )
cout << ",";
}

cout << " ] ";
}

cout << "\n";
}

system("PAUSE");
return EXIT_SUCCESS;
}

```

### #8 Skydiver

• Code herder

Reputation: 5898
• Posts: 20,138
• Joined: 05-May 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 03:56 AM

I'm going to bed... really...

Look closer at line 13 and 26, and 16 and 28. The correct lines are 26 and 28.

You can replace line 8 with:
```enum ColorIndex { red = 0, green = 1, blue = 2 };

```

To prevent further incidents like the line 13<->26 ad 16<->28 issue you could replace line 9 with:
```struct {
int rows;
int columns;
int cells;
} dimensions = { 5, 5, 3 };

```

and replace all instances of res[0] with dimensions.rows, etc.

### #9 DevonZ

Reputation: 6
• Posts: 73
• Joined: 04-August 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 05:33 AM

I've been working on a class assignment and have it nearly completed. However, I cannot seem to get a firm grasp on pointers and passing arrays between functions... When completed, the project will create a PPM image file of a rectangle on a 256x256px canvas. The user can define the position, size, and color of such rectangle. That's beside the point though, my problem is accessing the data in the pixMap array when in the writeToPPM functions scope.

Below is what I've coded thus-far. When the program gets to Line 100, it crashes when trying to parse pixMap[row][col][color]

```#include <iostream>
#include <fstream>

using namespace std;

void getParameters( int &x, int &y, int &width, int &height, int rgb[] );
void drawRectangle( int x, int y, int width, int height, int ***pixMap, int rgb[] );
void writeToPPM( int width, int height, int ***pixMap );

const bool DEBUG = true;
const int colorDepth = 15;
const int resolution[2] = { 256, 256 };
enum ColorIndex { red = 0, green = 1, blue = 2 };
enum SizeIndex { imgWidth = 0, imgHeight = 1 };

int main()
{
int x, y, width, height, rgb[3] = { 0 }, ***pixMap = NULL;

getParameters( x, y, width, height, rgb );
drawRectangle( x, y, width, height, pixMap, rgb );
writeToPPM( width, height, pixMap );

delete [] pixMap;
pixMap = NULL;

system("PAUSE");
return 0;
}

void getParameters( int &x, int &y, int &width, int &height, int rgb[] )
{
do
{
cout << "\nPlease enter the position of the top-left corner.\nEnter data (ex. 200 500 ): ";
cin >> x >> y;
} while( x <= 0 && x >= resolution[imgWidth] && y <= 0 && y >= resolution[imgHeight] );

do
{
cout << "\nPlease enter a width and height for your rectangle.\nEnter data (ex. 200 500 ): ";
cin >> width >> height;
} while( width <= 0 && width >= resolution[imgWidth] && height <= 0 && height >= resolution[imgHeight] );

do
{
cout << "\nPlease enter a red, green, and blue value for your rectangle.\nEnter data (ex. 4 6 15 ): ";
cin >> rgb[red] >> rgb[green] >> rgb[blue];
} while( ( rgb[red] >= 0 && rgb[red] <= colorDepth )
&& ( rgb[green] >= 0 && rgb[green] <= colorDepth )
&& ( rgb[blue] >= 0 && rgb[blue] <= colorDepth ) );
}

void drawRectangle( int x, int y, int width, int height, int ***pixMap, int rgb[] )
{
pixMap = new int **[resolution[imgHeight]]; // Rows
for (int row = resolution[imgHeight] - 1; row >= 0 ; row--)
{
pixMap[row] = new int *[resolution[imgWidth]]; // Cols
for (int col = 0; col < resolution[imgWidth]; col++)
{
pixMap[row][col] = new int [3]; // Cell Array

pixMap[row][col][red] = rgb[red];
pixMap[row][col][green] = rgb[green];
pixMap[row][col][blue] = rgb[blue];
}
}
}

void writeToPPM( int width, int height, int ***pixMap )
{
char outFilename[16];
ofstream outFile;

// Build the filename based on the current iteration.
//sprintf( outFilename, "output%d.ppm", i );
outFile.open( "image.ppm" );

// Check for error or write the data, close, and output
// a message to the screen.
if( !outFile )
cout << "Error opening file!";
else
{

if ( DEBUG )
cout << "P3\n" << resolution[imgWidth] << " " << resolution[imgHeight] << endl << colorDepth << endl;

outFile << "P3\n" << resolution[imgWidth] << " " << resolution[imgHeight] << endl << colorDepth << endl;

for ( int row = resolution[imgHeight] - 1; row >= 0; row-- )
{
for ( int col = 0; col < resolution[imgWidth]; col++ )
{
for ( int color = 0; color < 3; color++ )
{
if ( DEBUG )
{
cout << " - " << row << " - " << col << " - " << color << " - " << pixMap[row][col][color];
if ( color < 2 )
cout << " ";
}

outFile << pixMap[row][col][color];
if ( color < 2 )
outFile << " ";
}

if ( DEBUG )
cout << " ";

outFile << " ";
}

if ( DEBUG )
cout << "\n";

outFile << "\n";
}
}
}
```

Please be sure to be as detailed as possible with your answer as I am fairly new to this and I'm trying to learn.

Thanks

### #10 baavgai

• Dreaming Coder

Reputation: 6979
• Posts: 14,605
• Joined: 16-October 07

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 07:46 AM

You know, you invert your rows and cols when you print! It's easy to get away with that if they are the same value.

First thing, use functions. e.g.
```#include <iostream>

using namespace std;

int ***makeThing(int rows, int cols) {
const int arraySize = 3;
int ***a = NULL; // pointer of pointer of pointer to int(s)

a = new int**[rows]; // allocate pointer of pointer to int
for (int row = 0; row <rows; row++) {
a[row] = new int*[cols]; // allocate pointer to int
for (int col = 0; col < cols; col++) {
a[row][col] = new int [arraySize];    // allocate ints
a[row][col][0] = row;
a[row][col][1] = col;
a[row][col][2] = 3;
}
}
return a;
}

int showThing(int ***a, int rows, int cols) {
const int arraySize = 3;
for (int row = 0; row <rows; row++) {
for (int col = 0; col < cols; col++) {
cout << "[ ";
for ( int i = 0; i < arraySize; i++ ) {
if ( i!=0 ) { cout << ","; }
cout << a[row][col][i];
}
cout << " ]\n";
}
}
}

void deleteThing(int ***a, int rows, int cols) {
}

int main(int argc, char *argv[]) {
const int rows = 3;
const int cols = 4;
int ***a = makeThing(rows, cols);

cout << "\n\n== Now Let's View The Results ==\n\n\n";
showThing(a, rows, cols);
deleteThing(a, rows, cols);
return 0;
}

```

Better to actually use a struct for your 2D array, which is kind of what you're doing now.
e.g.
```#include <iostream>

using namespace std;

struct Color {
int red, green, blue;
};

Color **makeColorArray(int rows, int cols) {
Color **a = new Color*[rows];
for (int row = 0; row <rows; row++) {
a[row] = new Color[cols]; // allocate pointer to int
for (int col = 0; col < cols; col++) {
a[row][col].red = row;
a[row][col].green = col;
a[row][col].blue = 3;
}
}
return a;
}

ostream &operator<<(ostream &out, const Color &c) {
out << '[' << c.red << ',' << c.green << ',' << c.blue << ']';
return out;
}

void showColorArray(Color **a, int rows, int cols) {
for (int row = 0; row <rows; row++) {
for (int col = 0; col < cols; col++) {
cout << a[row][col] << endl;
}
}
}

void deleteColorArray(Color **a, int rows, int cols) {
}

int main(int argc, char *argv[]) {
const int rows = 3;
const int cols = 4;
Color **a = makeColorArray(rows, cols);

showColorArray(a, rows, cols);
deleteColorArray(a, rows, cols);

return 0;
}

```

For extra credit, you could wrap everything up in an object and avoid that potention memory leak.
```struct ColorArray {
int rows, cols;
Color **data;
ColorArray(int rows, int cols);
~ColorArray();
void print();
}

```

Hope this helps;

### #11 DevonZ

Reputation: 6
• Posts: 73
• Joined: 04-August 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 08:00 AM

baavgai,

I appreciate your insight. However, because I'm just learning - I'm going to stick with the basics as we've not yet covered structs, enums, or objects in class. I vaguely know about them from my experience with PHP and other articles I've read. However, my professor still makes us structure our programs with pre-defined function names that he's made up and the main goal of this assignment is to gain experience with multidimensional arrays. Hopefully though, as things progress, we're given more flexibility.

I would love your help/insight in [ my other topic ] pertaining to this same assignment.

Thanks!

### #12 jimblumberg

Reputation: 5336
• Posts: 16,617
• Joined: 25-December 09

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 08:01 AM

What are the values of your variables row, col, and color at the time of the crash. If your cout statement doesn't show, put the print of the array on a different line.

Jim

### #13 DevonZ

Reputation: 6
• Posts: 73
• Joined: 04-August 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 08:15 AM

Erm, why were my two topics merged? My second topic was not related to this and now that question is completely gone. I don't appreciate having to retype my question nor spamming this thread which had already be resolved. But since I'm left with no choice...

jimblumberg,

As I was trying to say before my topic was deleted/merged.

Quote

They do show and they are accurate.

255 - 0 - <what ever is entered> -

Thanks

The assignment consists of having to output a PPM images file 256x256px in size with a rectangle drawn on it. The user is prompted for the location, size, and color of the rectangle. The code then creates an array for them image and creates the PPM file. I understand how to break it down and complete the assignment, that's not a problem. My problem is with getting the values of a the pixMap array in the WriteToPPM functions scope.

The error occurs on Line 100 when parsing pixMap[row][col][color]

Here is the code I have thus-far:
```#include <iostream>
#include <fstream>

using namespace std;

void getParameters( int &x, int &y, int &width, int &height, int rgb[] );
void drawRectangle( int x, int y, int width, int height, int ***pixMap, int rgb[] );
void writeToPPM( int width, int height, int ***pixMap );

const bool DEBUG = true;
const int colorDepth = 15;
const int resolution[2] = { 256, 256 };
enum ColorIndex { red = 0, green = 1, blue = 2 };
enum SizeIndex { imgWidth = 0, imgHeight = 1 };

int main()
{
int x, y, width, height, rgb[3] = { 0 }, ***pixMap = NULL;

getParameters( x, y, width, height, rgb );
drawRectangle( x, y, width, height, pixMap, rgb );
writeToPPM( width, height, pixMap );

delete [] pixMap;
pixMap = NULL;

system("PAUSE");
return 0;
}

void getParameters( int &x, int &y, int &width, int &height, int rgb[] )
{
do
{
cout << "\nPlease enter the position of the top-left corner.\nEnter data (ex. 200 500 ): ";
cin >> x >> y;
} while( x <= 0 && x >= resolution[imgWidth] && y <= 0 && y >= resolution[imgHeight] );

do
{
cout << "\nPlease enter a width and height for your rectangle.\nEnter data (ex. 200 500 ): ";
cin >> width >> height;
} while( width <= 0 && width >= resolution[imgWidth] && height <= 0 && height >= resolution[imgHeight] );

do
{
cout << "\nPlease enter a red, green, and blue value for your rectangle.\nEnter data (ex. 4 6 15 ): ";
cin >> rgb[red] >> rgb[green] >> rgb[blue];
} while( ( rgb[red] >= 0 && rgb[red] <= colorDepth )
&& ( rgb[green] >= 0 && rgb[green] <= colorDepth )
&& ( rgb[blue] >= 0 && rgb[blue] <= colorDepth ) );
}

void drawRectangle( int x, int y, int width, int height, int ***pixMap, int rgb[] )
{
pixMap = new int **[resolution[imgHeight]]; // Rows
for (int row = resolution[imgHeight] - 1; row >= 0 ; row--)
{
pixMap[row] = new int *[resolution[imgWidth]]; // Cols
for (int col = 0; col < resolution[imgWidth]; col++)
{
pixMap[row][col] = new int [3]; // Cell Array

pixMap[row][col][red] = rgb[red];
pixMap[row][col][green] = rgb[green];
pixMap[row][col][blue] = rgb[blue];
}
}
}

void writeToPPM( int width, int height, int ***pixMap )
{
char outFilename[16];
ofstream outFile;

// Build the filename based on the current iteration.
//sprintf( outFilename, "output%d.ppm", i );
outFile.open( "image.ppm" );

// Check for error or write the data, close, and output
// a message to the screen.
if( !outFile )
cout << "Error opening file!";
else
{

if ( DEBUG )
cout << "P3\n" << resolution[imgWidth] << " " << resolution[imgHeight] << endl << colorDepth << endl;

outFile << "P3\n" << resolution[imgWidth] << " " << resolution[imgHeight] << endl << colorDepth << endl;

for ( int row = resolution[imgHeight] - 1; row >= 0; row-- )
{
for ( int col = 0; col < resolution[imgWidth]; col++ )
{
for ( int color = 0; color < 3; color++ )
{
if ( DEBUG )
{
cout << " - " << row << " - " << col << " - " << color << " - " << pixMap[row][col][color];
if ( color < 2 )
cout << " ";
}

outFile << pixMap[row][col][color];
if ( color < 2 )
outFile << " ";
}

if ( DEBUG )
cout << " ";

outFile << " ";
}

if ( DEBUG )
cout << "\n";

outFile << "\n";
}
}
}
```

### #14 jimblumberg

Reputation: 5336
• Posts: 16,617
• Joined: 25-December 09

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 08:23 AM

You're printing the values of your indexes on the same line you are saying is crashing, what are those values at the time of the crash?

Jim

### #15 DevonZ

Reputation: 6
• Posts: 73
• Joined: 04-August 12

## Re: Understanding Dynamic Multidimensional Arrays

Posted 05 August 2012 - 08:40 AM

jimblumberg,

As I stated in my last message:

Quote

255 - 0 - <what ever is entered>

Thanks