Two Dimensional Arrays

C

cplusplusquestion

There is a two-dimensional array:

int grades[MAX][MAX];
for( i = 0; i < MAX; i++)
for( j = 0; j < MAX; j++)
grades[j] = -1;


I would like to assign an another variable to this array, for example:

int another_grades[MAX][MAX];
for( i = 0; i < MAX; i++)
for( j = 0; j < MAX; j++)
another_grades[j] = grades[j];

Here, I need to declare another array. Is it possible to have a
pointer to point grades[MAX][MAX]? As I've tried:

int** another_g = grades;

it does not work. Any good idea?
 
T

Tim Love

M

Michael.Boehnisch

There is a two-dimensional array:

int grades[MAX][MAX];
for( i = 0; i < MAX; i++)
for( j = 0; j < MAX; j++)
grades[j] = -1;

I would like to assign an another variable to this array, for example:

int another_grades[MAX][MAX];
for( i = 0; i < MAX; i++)
for( j = 0; j < MAX; j++)
another_grades[j] = grades[j];

Here, I need to declare another array. Is it possible to have a
pointer to point grades[MAX][MAX]? As I've tried:

int** another_g = grades;

it does not work. Any good idea?


While native arrays are perfectly legal C++, I recommend to use one of
the standard classes std::vector<> or std::valarray<> instead. There
is no performance penalty in using them and only a very small increase
in memory footprint. The benefits by far outweigh the tiny overhead.

I would change your code like this:

#include <vector>
....
std::vector< std::vector<int> > grades( MAX, std::vector<int>( MAX,
-1 ) );
// initializes all elements to -1, no explicit loops!

std::vector< std::vector<int> > another_grades1 = grades;
// copy the whole 2D array to another location.

std::vector< std::vector<int> >& another_grades2 = grades;
// create a reference (implicit pointer) variable to the same
location.

std::vector< std::vector<int> >* another_grades3 = &grades;
// create an explicit pointer to the 2D array.

Access to the std::vector elements looks the same as with native
arrays:

grades[5][3] = 1;
another_grades1[3][5] = 2;
another_grades2[1][1] = 3;
(*another_grades3)[0][0] = 4;

std::valarray<> is an alternative with access methods optimized for
linear algebra at the expense of a less intuitive interface.

best,

Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top