Converting an array to a multidimensional one

S

Slain

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
int *x;

in a initialize function:
x = new int[$Row_Length];

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?

Thank you
 
S

Salt_Peter

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
int *x;

in a initialize function:
x = new int[$Row_Length];

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?

Thank you

Use a vector of vectors instead, much easier and it brings many
dividends (its dynamic, easy to extend - like providing iterators to
the interface). Instead of dealing with heap allocated pointers that
blindly point to whatever in an exception-unsafe way, deal with
objects instead.

// array2d.h, missing include guard

#include <vector>

class Array2D
{
typedef std::vector< int > VecN;
// members
std::vector< VecN > m_vvn; // 2D array
public:
// ctors
Array2D(std::size_t, std::size_t);
Array2D(std::size_t, std::size_t, const int);
// member functions
std::size_t size() const { return m_vvn.size(); }
VecN operator[](std::size_t index) { return m_vvn[index]; }
void display() const;
};

// array2d.cpp

#include <iostream>
#include <algorithm>
#include <iterator>
#include "array2d.h"

Array2D::Array2D(std::size_t rows, std::size_t cols)
: m_vvn(rows, std::vector< int >(cols)) { }

Array2D::Array2D(std::size_t rows, std::size_t cols, const int n)
: m_vvn(rows, std::vector< int >(cols, n)) { }

void Array2D::display() const
{
typedef std::vector< VecN >::const_iterator VIter;
for(VIter it = m_vvn.begin(); it != m_vvn.end(); ++it)
{
std::copy( (*it).begin(),
(*it).end(),
std::eek:stream_iterator< int >(std::cout, " ") );
std::cout << std::endl;
}
}

// main.cpp
#include "array2d.h"

int main()
{
Array2D a2d(4, 4, 99);
std::cout << "rows: " << a2d.size() << std::endl;
std::cout << "columns: " << a2d[0].size() << std::endl;
a2d.display();
}

/*
rows: 4
columns: 4
99 99 99 99
99 99 99 99
99 99 99 99
99 99 99 99
*/
 
M

Maxim Yegorushkin

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
int *x;

No need to modify the declaration. Multidimensional arrays in C++ are
stored as one-dimensional arrays anyway.

What you need to modify is how you calculate one-dimensional index.
in a initialize function:
x = new int[$Row_Length];

$Row_Length - is that a shell or Perl variable in here? ;)
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];
 
J

James Kanze

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
index.
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
you described.)
 
M

Maxim Yegorushkin

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).


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.

Yes, you can:

int(*x)[Cols] = new int[Rows][Cols];
// let's represent it as a plain array
int* y = x[0] + 0;
(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.)

In C++ one-dimensional and multi-dimensional arrays are different
names for the same thing - a contiguous block of memory. Using
language constructs one can view that block as a one-dimensional or
multi-dimensional array. Nevertheless, it is still fundamentally the
same thing in C and C++.
 
S

Slain

On Nov 19, 10:12 am, Maxim Yegorushkin <[email protected]>
wrote:
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).
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.

Yes, you can:

    int(*x)[Cols] = new int[Rows][Cols];
    // let's represent it as a plain array
    int* y = x[0] + 0;
(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.)

In C++ one-dimensional and multi-dimensional arrays are different
names for the same thing - a contiguous block of memory. Using
language constructs one can view that block as a one-dimensional or
multi-dimensional array. Nevertheless, it is still fundamentally the
same thing in C and C++.

Thanks Max and James and the others!!!
We don't ahve STL's :(

I would eprsonally want to go ahead with the single dimensional
approach which max suggested, but that is becase I am an electrical
engineer. I think since this fits into existing code, I would have it
access elements much like a two dimensional array. It would be much
easier for the future person dealing with it.

The Row_Length was just means to provide that a fixed value will go in
there.

I think I will try James approach. Thank you guys!!! I might come abck
with more questions :)

Thanks a lot
 
J

James Kanze

Yes, you can:
int(*x)[Cols] = new int[Rows][Cols];
// let's represent it as a plain array
int* y = x[0] + 0;

I'm not quite sure what the + 0 is doing there; it changes
absolutely nothing. But all you've got is still a pointer to
the first element of x[0]; an expression like y[Rows+1] is
undefined behavior.
In C++ one-dimensional and multi-dimensional arrays are
different names for the same thing - a contiguous block of
memory.

That's simply false. In C++, arrays have a type; they're not
just a block of (raw) memory. And that type includes the
dimension.
Using language constructs one can view that block as a
one-dimensional or multi-dimensional array.

Not without invoking undefined behavior.
Nevertheless, it is still fundamentally the same thing in C
and C++.

That's true. The C standard was carefully written to allow
bounds checking. I only know of one implementation which ever
did it, but the standard is clear; it's legal, and anything that
would cause a bounds check error is undefined behavior.
 
M

Maxim Yegorushkin

On Nov 19, 10:12 am, Maxim Yegorushkin
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
int *x;
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.
Yes, you can:
    int(*x)[Cols] = new int[Rows][Cols];
    // let's represent it as a plain array
    int* y = x[0] + 0;

I'm not quite sure what the + 0 is doing there;

It is a shortcut for:

int* y = &x[0][0];
it changes absolutely nothing.
 But all you've got is still a pointer to
the first element of x[0];

You are right that x[0] is sufficient.
an expression like y[Rows+1] is undefined behavior.

It is just meaningless.
That's simply false.  In C++, arrays have a type; they're not
just a block of (raw) memory.  And that type includes the
dimension.

There are two separate issues: type and binary layout.

You are quite right that the types are distinct and unrelated
according to the standard, and thus casting is formally undefined
behaviour.

The binary layout is quite a different story. Size of an object is
always a multiple of its alignment. The size is defined this way, so
that when objects are stored in an array there is no padding between
the objects. Thus, the size of a one-dimensional array is nothing more
than the size of an element multiplied by the number of elements.

In a multi-dimensional array the elements are arrays. Due to the
requirement that there be no padding between the elements of an array,
there is no padding between elements-arrays of a multi-dimensional
array. Thus, multi-dimensional arrays can not be stored any other way,
but exactly as a single-dimensional array with the number of elements
equal to the total number of elements of the multi-dimensional array.

Essentially, the standard implicitly guarantees that the binary
layouts of arrays with the same underlying object type but with
different dimensions are the same as long as the total number of the
objects is the same.
Not without invoking undefined behavior.

On one hand the standard says that the casting between arrays of
different dimensions is undefined behaviour, on the other hand it
provides the aforementioned binary layout guarantees. In my opinion,
it is an underspecification or inconsistency of the standard.
 

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

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top