Archive for the ‘ CPP ’ Category

Dynamic Three Dimensional Arrays in C\C++\C#\Java


If you come from a Java or C# perspective and want to create a multi-dimensional array in C or C++, you’ll soon figure out that multi-dimensional array allocation in C\C++ is not as simple, plus you’ll have to worry about deallocation since there is no garbage collector to do the work for you. Below I’ll show four different sample codes showing how to work with a three dimensional array in Java, C#, C++ and C, respectively.

Java 3D Array

In Java, creating a 3-dimensional array is as simple as saying

int[][][] array3D = new int[x][y][z];

You can then access the elements of the 3-dimensional array at array3D[i][j][k].

Sample Code

public static void main(String[] args)
{
    //  Array 3 Dimensions
    int x = 4, y = 5, z = 6;

    //  Array Iterators
    int i, j, k;

    //  Allocate 3D Array
    int[][][] array3D = new int[x][y][z];

    //  Access array elements
    for (i = 0; i < x; i++)
    {
        System.out.println(i);

        for (j = 0; j < y; j++)
        {
            System.out.println();

            for (k = 0; k < z; k++)
            {
                array3D[i][j][k] = (i * y * z) + (j * z) + k;
                System.out.print("\t" + array3D[i][j][k]);
            }
        }

        System.out.println('\n');
    }
}

C# 3D Array

In C#, the concept is almost the same as in Java. However, C# makes the distinction between jagged and multi-dimensional arrays. Elements of a multi-dimensional array are stored in a contiguous block in memory while elements of a jagged array are not. Java arrays are actually jagged arrays, while C# supports both and allows you to choose which one you want based on the syntax of your code. Note that multi-dimensional arrays are better (in most cases) than jagged arrays, and that is considered a minus point for Java.

Using jagged arrays in C# is not as simple as in Java. It’s almost like the way we would implement it in C++.

int[][] jaggedArray = new int[2][];
jaggedArray[0] = new int[4];
jaggedArray[1] = new int[3];

However, multi-dimensional arrays in C# are very simply to use. You can create a 3 dimensional array as follows

int[,,] array3D = new int[x, y, z];

then access its elements at array3D[i][j][k].

Sample Code

static void Main(string[] args)
{
    //  Array 3 Dimensions
    int x = 4, y = 5, z = 6;

    //  Array Iterators
    int i, j, k;

    //  Allocate 3D Array
    int[,,] array3D = new int[x, y, z];

    //  Access array elements
    for (i = 0; i < x; i++)
    {
        Console.WriteLine(i);

        for (j = 0; j < y; j++)
        {
            Console.WriteLine();

            for (k = 0; k < z; k++)
            {
                array3D[i, j, k] = (i * y * z) + (j * z) + k;
                Console.Write("\t{0}", array3D[i, j, k]);
            }
        }

        Console.WriteLine('\n');
    }
}

C++ 3D Array

To create a multi-dimensional array in C++, we should change perspective a little bit and think of creating arrays that point to other arrays, which point to other arrays, and so on. For example, to create a 2x3x4 array in C++, we should imagine the implementation as follows:

For simplicity, we are doing the jagged implementation of the multi-dimensional array (address of array3d[0][1][0] is not directly after array3d[0][0][3] in memory representation above). In the next section, we will implement it in C the contiguous way. To allocate a jagged 2D array in C++, one can write the following (compare to C# jagged above):

int** jaggedArray = new int*[2];
jaggedArray[0] = new int[4];
jaggedArray[1] = new int[3];

The elements can be accessed as usual: jaggedArray[i][j]. The extra work we have to do in C++ is to explicitly deallocate the array.

delete[] jaggedArray[0];
delete[] jaggedArray[1];
delete[] jaggedArray;

See the code sample below to understand how we allocate and deallocate a 3 dimensional array in C++.

Sample Code

#include <iostream>

using namespace std;

void main()
{
    //  Array 3 Dimensions
    int x = 4, y = 5, z = 6;

    //  Array Iterators
    int i, j, k;

    //  Allocate 3D Array
    int ***array3D = new int**[x];

    for(i = 0; i < x; i++)
    {
        array3D[i] = new int*[y];

        for(j = 0; j < y; j++)
        {
            array3D[i][j] = new int[z];
        }
    }

    //  Access array elements
    for(i = 0; i < x; i++)
    {
        cout << i << endl;

        for(j = 0; j < y; j++)
        {
            cout << endl;

            for(k = 0; k < z; k++)
            {
                array3D[i][j][k] = (i * y * z) + (j * z) + k;
                cout << '\t' << array3D[i][j][k];
            }
        }

        cout << endl << endl;
    }

    //  Deallocate 3D array
    for(i = 0; i < x; i++)
    {
        for(j = 0; j < y; j++)
        {
            delete[] array3D[i][j];
        }

        delete[] array3D[i];
    }
    delete[] array3D;
}

C 3D Array

Implementing multi-dimensional arrays in C is very similar to C++, except that we use malloc()\free()  stdlib methods instead of the new\delete keywords. The memory representation below is the same, but we are going to focus in this section on making the elements of the 3 dimensional array contiguous.

To do so, we start by allocating space for all array elements in one call to malloc.

int *allElements = malloc(x * y * z * sizeof(int));

Next, we create the arrays of pointers, and point to the contiguous elements we’ve already allocated.

int ***array3D = malloc(x * sizeof(int **));
for(i = 0; i < x; i++)
{
    array3D[i] = malloc(y * sizeof(int *));

    for(j = 0; j < y; j++)
    {
        array3D[i][j] = allElements + (i * y * z) + (j * z);
    }
}

Note that if we wanted the same jagged implementation as in the C++ example above, we could ignore the allocation of allElements and change the line of code array3D[i][j] = allElements + (i * y * z) + (j * z); to array3D[i][j] = malloc(z * sizeof(int)). Below is a sample code for allocating, accessing and deallocating a 3 dimensional array in C.

#include <stdio.h>
#include <stdlib.h>

void main()
{
    //  Array 3 Dimensions
    int x = 4, y = 5, z = 6;

    //  Array Iterators
    int i, j, k;

    //  Allocate 3D Array
    int *allElements = malloc(x * y * z * sizeof(int));
    int ***array3D = malloc(x * sizeof(int **));

    for(i = 0; i < x; i++)
    {
        array3D[i] = malloc(y * sizeof(int *));

        for(j = 0; j < y; j++)
        {
            array3D[i][j] = allElements + (i * y * z) + (j * z);
        }
    }

    //  Access array elements
    for(i = 0; i < x; i++)
    {
        printf("%d\n", i);

        for(j = 0; j < y; j++)
        {
            printf("\n");

            for(k = 0; k < z; k++)
            {
                array3D[i][j][k] = (i * y * z) + (j * z) + k;
                printf("\t%d", array3D[i][j][k]);
            }
        }

        printf("\n\n");
    }

    //  Deallocate 3D array
    free(allElements);
    for(i = 0; i < x; i++)
    {
        free(array3D[i]);
    }
    free (array3D);
}

Source Code

Full source code for the above 4 samples is available here.

GLUI Subwindow Template


This article shows you how to create GUI controls for your OpenGL application and organize them into GLUI subwindows. In this article, we will take the source code from the previous article GLUI Window Template, and modify it so that our GLUI controls will be laid out inside two subwindows rather than in a single window. The reason is that having a separate window to contain our GLUI controls could be sometimes annoying for the user, as she or he will have to lose the focus on the OpenGL context window every time she or he wants to do an action. A nice way to avoid this is to place the GLUI controls directly into the GLUT OpenGL window by embedding them into a GLUI subwindow.

This article can be used in the following ways:

  • Learn how to use GLUI subwindows
  • Understand the Viewport concept in OpenGl
  • Use the program as a template for your OpenGL applications that require GUI controls

The image below shows how our controls were laid out into a single GLUI window in the previous article:

GLUI Window

The image below shows how our controls will be laid out into two separate subwindows placed on the left and the bottom of our main GLUT window:

GLUI Subwindow

Check it out, and let me know your feedback.

Enjoy!
Ali B

GLUI Window Template


This article describes in detail how to create your first GLUI window with some basic controls inside it, and provides you with a template for your OpenGL applications.

When OpenGL applications get more complex, we need something more than a GLUT mouse, keyboard, and\or popup menus to interact with our OpenGL objects drawn on the window. GLUI gives us more flexibility by allowing us to add GUI components to interact with our OpenGL objects, such as buttons, check boxes, radio buttons, spinners, list boxes, lists, trees, file browsers, text fields, text areas, and the special controls: rotation and translation.

This article can be used in the following ways:

  • Learn how to add GUI components to your OpenGL application in a very straight-forward and simple manner, through
    • Documentation
    • Interactive Program that displays to the user how every event is handled and classifies these events into GLUT and GLUI events.
    • Neat and commented Code that reflects the simplicity of the GLUI library
  • Learn some totally new controls in the GLUI library created specifically for graphical manipulation, such as the rotation and translation controls.
  • Use the code as a template for your OpenGL applications.

Click below for a screen shot of what the program would look like when its run.

GLUI Window Template

Make sure you read the GLUT Window Template article as a prerequisite to this article. One important thing to note is that GLUI is a C++ library, which means that your code must be written in files with .cpp extension rather than .C, or otherwise the linker will complain.

Check it out, and let me know your feedback.

Enjoy!
Ali B

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: