Up

Multidimensional Array in C++ and in Visual C++/CLR(CLI)

 

A simple sample program, which shows how to use multidimensional array in C++ or in C++/CLR, was prepared.

 

#include <string>

#include <sstream>

#include <iostream>

 

using namespace System;

using namespace std;

 

int main(array<System::String ^> ^args)

{

        array<array<String^>^>^ a;

        a = gcnew array<array<String^>^>(2);

        for (int i = 0; i < 2; i++)

                a[i] = gcnew array<String^>(3);

 

        for (int i = 0; i < 2; i++)

                for (int j = 0; j < 3; j++)

                        a[i][j] = "Row-" + i.ToString() + ", Column-" + j.ToString();

 

        for (int i = 0; i < 2; i++)

                for (int j = 0; j < 3; j++)

                        Console::WriteLine(a[i][j]);

 

        string ** sa;

        sa = new string*[2];

        for (int i = 0; i < 2; i++)

                sa[i] = new string[3];

 

        for (int i = 0; i < 2; i++)

                for (int j = 0; j < 3; j++){

                        ostringstream strm;

                        strm << "Row-" << i << ", Column-" << j;

                        sa[i][j] = strm.str();

                }

 

        cout << endl;

        for (int i = 0; i < 2; i++)

                for (int j = 0; j < 3; j++)

                        cout << sa[i][j] << endl;

 

        for (int i = 0; i < 2; i++)

                delete[] sa[i];

        delete[] sa;

 

        Console::WriteLine();

        Console::WriteLine("Press Enter-key.");

        Console::ReadLine();

    return 0;

}

 

The above program can be built and run on Visual Studio 2013.

Figure 1 shows the console window, which will appear during the execution.

Figure 1

 

A sample program, which uses stringstream and ostringstream classes, is prepared at this website.

 

Up