Solved

How to create a multi-dimension array in C Plus Plus

Posted on 2009-04-02
17
867 Views
Last Modified: 2012-05-06
I need some help to create a multi-dimension array in C Plus Plus, but the user have to input the size of the array n x n.
The array has to be in simple C Plus Plus code with no class creation.
I try to make some thing like this, but dont work.

int main ()
{
    int a, b;
    int matriz[a][b];
    cout<<"Define the size of the matrix.\n";
      cin >> a;
      b=a;
}
But because i´m a noob on programming i can´t make it work. Please can you give me some help or directions.
Appreciated.
0
Comment
Question by:David Paris Vicente
  • 5
  • 4
  • 4
  • +3
17 Comments
 
LVL 40

Assisted Solution

by:mrjoltcola
mrjoltcola earned 300 total points
ID: 24055810
Read the numbers in first, then create the array.
You are doing it backwards.
0
 
LVL 5

Assisted Solution

by:rendaduiyan
rendaduiyan earned 50 total points
ID: 24056791
1) create a array of size n, but they are pointers.
2) foreach pointer in this array, create a array to be pointed by this pointer.
int ** pa = new int [n];
for()
....
0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 100 total points
ID: 24057695
>>     int matriz[a][b];

You can't create a static array with runtime dimensions. You'll need to use a dynamically allocated array.

Take a look at this tutorial :

        http://www.cplusplus.com/doc/tutorial/dynamic.html
0
 

Expert Comment

by:errang
ID: 24057726
Would this work?

int main (int argc, char **argv)
{
    int a = atoi(argv[1])
    int b = atoi(argv[2]);
    int matriz[a][b];
}

With this you'd have to enter the dimensions of the array as a command line argument.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 24057827
Right ... C++, not C ... Ignore my previous post please :)
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 24058793
>>>> Right ... C++, not C ... Ignore my previous post please :)

Most nowadays C++ compilers won't allow definition of an array with non-const size parameters (though a next standard might require that)

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 24059071
>> Most nowadays C++ compilers won't allow definition of an array with non-const size parameters

It seems I have been spoiled by g++ which supports it as an extension.

Variable length arrays are allowed in C99, but are not covered by the C++ standard. So, my initial response was correct after all (I should rely on my intuition a bit more lol).

You have to use dynamically allocated memory for variable length arrays in C++, unless you want to make use of a compiler extension like g++ has.
0
 
LVL 12

Author Comment

by:David Paris Vicente
ID: 24059085
Yes it´s in C++.
errang, that don´t work .
I´m trying to make the game Tic Tac Toe but the user have to input the size of the matrix.
If the matrix is static is easy but they want the matrix dynamic.
I made this when i saw some examples, but i don´t understand.

#include <iostream>
using namespace std;
 
int main ()
{
int i=0,a,b;
int **matrix;
cout<< "Insert the size of the Matrix.\n";
cin>>a;
b=a;

matrix= new int*[a];
for (i; i<a;i++)
{
matrix[i]= new int [b];
}

system ("PAUSE");
return 0;
}
And how can i send some information to inside, i cant visualize in my mind how this works.
Thank you all.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 53

Expert Comment

by:Infinity08
ID: 24059319
>> I made this when i saw some examples, but i don´t understand.

That looks ok. It creates a dynamically allocated 2-dimensional array. For more information, see the tutorial I mentioned earlier.

You can access the dynamically allocated array, in the same way as you access a normal array, ie. matrix[i][j] will get the value at row i, column j.
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 50 total points
ID: 24059696
>> I made this when i saw some examples, but i don´t understand

>>>> matrix= new int*[a];

that creates an array of pointers which are supposed to point to the first element of a row.

>>>> matrix[i]= new int [b];

that creates an array of int for row with index i and the pointer to that array was assigned to the rows array:

matrix             0  1  2  ... b-1
[row 0]    ->   [] [] []  ...  []
[row 1]    ->   [] [] []  ...  []
....
[row a-1] ->   [] [] []  ...  []

So actually the matrix is an array of pointers  (the left column in the diagram) and the second index works horizontal for each row (pointer).

for a fixed-sized matrix it is different:

const int a = 4;
const int b = 5;
int matrix[a][b] = { 0 };

0  1  2 3 4
[] [] [] [] []
[] [] [] [] []
[] [] [] [] []
[] [] [] [] []

Here we have no additional pointer array but only one int array of 20 elements accessible as 4 rows with 5 columns each.

Nevertheless for both we have the same expression when accessing one single element:

    matrix[2][3] = 12345;



0
 
LVL 12

Author Comment

by:David Paris Vicente
ID: 24061680
I´m gone try.
Thanks
0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24061822
Another approach is to just allocate it in a linear 1 dimensional array, and write an "access(arr, row, col)" method. Arrays are laid out like that anyway.

int *matrix = new int[ ROWSIZE * COLSIZE ];

int access(int * matrix, int row, int col) {
    return matrix[ ROWSIZE * row + col];
}
0
 
LVL 12

Author Comment

by:David Paris Vicente
ID: 24063807
I believe is this that i want>

void matriz()
{
int a,b,c=1;
int **matrix;
cout<< "Insert the size of the Matrix.\n";
cin>>a;
b=a;

for (int i=0; i<a;++i)
{
matrix= new int*[a];
for (int j=0; j<a; ++j)
{
matrix[i]= new int [b];
matrix[i][j]= c;
c++;
cout <<matrix[i][j]<<" ";
}
cout << endl;
}
}
Maybe it´s not the write way but it work.
Can you give me your feedback please.
If you agree with this way i will close this question and give the points.
Thank you all
0
 
LVL 40

Assisted Solution

by:mrjoltcola
mrjoltcola earned 300 total points
ID: 24063858
Thats not what you want because the statement:

   matrix = new int *[a];

is _inside_ a for loop. So it will overwrite matrix each time. Move that statement above the loop.

After that, I think it looks good.
0
 
LVL 40

Accepted Solution

by:
mrjoltcola earned 300 total points
ID: 24063987
Now, I will show you the trick I was referring to, which is something C programmers may do more than C++, but it is more memory and cache efficient than an array of pointers to arrays, and is one less level of indirection, because it allocates a single contiguous array. I'm not recommending you go this route, I would use an stl component, myself, but its worth knowing how to do this as an alternative.

void matrix()
{
  int a,b,c=1;
  int *matrix;
  cout<< "Insert the size of the Matrix.\n";
  cin>>a;
  b=a;

  matrix= new int[a * b];
  for (int i=0; i<a;++i)
  {
    for (int j=0; j<a; ++j)
    {
      matrix[i*a + j]= c;
      c++;
      cout <<matrix[i * a + j]<<" ";
    }
    cout << endl;
  }

  delete [] matrix;
}
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 24064415
>> I believe is this that i want>

As mrjoltcola already pointed out, there are a few problems with that code, memory leaks not being the least of it. But note that you posted correct code earlier here : http:#24059085. Why change that ?
0
 
LVL 12

Author Closing Comment

by:David Paris Vicente
ID: 31566047
Thanks to you all.
Antoher Question it is possible to call another function inside of a function?
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now