Re: Converting an array to a multidimensional one
On Nov 19, 10:12 am, Maxim Yegorushkin <maxim.yegorush...@gmail.com>
On Nov 19, 2:14 am, Slain <Slai...@gmail.com> wrote:
I need to convert a an array to a multidimensional one.
Since I need to wrok with existing code, I need to modify a
declaration which looks like this
In the .h file
Note that if this .h file is included in more than one file,
you'll get undefined behavior (and normally, multiple definition
errors when linking).
No need to modify the declaration. Multidimensional arrays in
C++ are stored as one-dimensional arrays anyway.
That's only true in the most superficial sense. You can't
access a multidimensional array as a one-dimensional array; the
two are different things.
(Formally speaking, of course, C++ doesn't have multidimensional
arrays. But it allows arrays of any type, including array
types, and an array of arrays works pretty much like a
multidimensional array for most things.)
What you need to modify is how you calculate one-dimensional
in a initialize function:
x = new int[$Row_Length];
$Row_Length - is that a shell or Perl variable in here? ;)
Or a typo; he uses Row_Length without the $ later.
Now I need the x to be able to point to a multidimensional
array I would ahve been fine, with something like
int (*x)[Column_Length] = new int [Row_Length][Column_Length];
But since my variable x needs to be declated in the header
file, I am having some problems compiling. Can some one
explain me how to declare and initialize?
You allocate your two-dimensional array like this:
int* x = new int[Row_Length * Column_Length];
And index into it like this:
int row, col; // initialised elsewhere
// access an element at x[row][col]
int& elem = x[row * Column_Length + col];
That's not a two dimensional array; that's just a method of
simulating one. While there are definitely cases where this
approach is recommended (or even necessisary), if his dimensions
(or at least Column_Length) is a constant, he can also write:
extern int (*x)[ Column_Length ] ;
in the header, and use
int (*x)[ Column_Length ] = new[ Row_Length ][ Column_Length ] ;
to initialize it.
Of course, a better solution might be to define a Matrix class,
and use that. With an implementation based on std::vector.
(Probably a one dimensional vector, calculating the indexes as
James Kanze (GABI Software) email:email@example.com
Conseils en informatique orient=C3=A9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=C3=A9mard, 78210 St.-Cyr-l'=C3?cole, France, +33 (0)1 30 23 00 34