473,699 Members | 3,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting an array to a multidimensiona l one

I need to convert a an array to a multidimensiona l 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 multidimensiona l 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
Nov 19 '08 #1
9 4495
Slain wrote:
I need to convert a an array to a multidimensiona l 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 multidimensiona l 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?
Have you tried looking in the FAQ?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 19 '08 #2
Sam
Slain writes:
I need to convert a an array to a multidimensiona l 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 multidimensiona l 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?
In C++ proper, you should be using std::vector, rather than old-fashioned C
arrays. Your declaration should be:

std::vector<std ::vector<int x;

Then:

x.resize(4);

Four rows.

x[0].resize(3);
x[1].resize(3);
x[2].resize(3);
x[3].resize(3);

Each row is initialized to a three-element array, giving you an
two-dimensional array of four rows and three columns, accessed as:

x[row][col];

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEABECAAYFAkk jfRwACgkQx9p3GY HlUOKDHwCeJwQYS OVEbfiojPBtqZ94 r76F
ccAAnjwui67mZgl snMpXaDzAwsqZU1 LB
=yV1Z
-----END PGP SIGNATURE-----

Nov 19 '08 #3
On Nov 18, 9:14 pm, Slain <Slai...@gmail. comwrote:
I need to convert a an array to a multidimensiona l 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 multidimensiona l 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::si ze_t, std::size_t);
Array2D(std::si ze_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::Array2 D(std::size_t rows, std::size_t cols)
: m_vvn(rows, std::vector< int >(cols)) { }

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

void Array2D::displa y() const
{
typedef std::vector< VecN >::const_iterat or VIter;
for(VIter it = m_vvn.begin(); it != m_vvn.end(); ++it)
{
std::copy( (*it).begin(),
(*it).end(),
std::ostream_it erator< 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
*/
Nov 19 '08 #4
On Nov 19, 2:14*am, Slain <Slai...@gmail. comwrote:
I need to convert a an array to a multidimensiona l 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. Multidimensiona l 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 multidimensiona l 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];

--
Max
Nov 19 '08 #5
On Nov 19, 10:12 am, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
wrote:
On Nov 19, 2:14 am, Slain <Slai...@gmail. comwrote:
I need to convert a an array to a multidimensiona l 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. Multidimensiona l arrays in
C++ are stored as one-dimensional arrays anyway.
That's only true in the most superficial sense. You can't
access a multidimensiona l array as a one-dimensional array; the
two are different things.

(Formally speaking, of course, C++ doesn't have multidimensiona l
arrays. But it allows arrays of any type, including array
types, and an array of arrays works pretty much like a
multidimensiona l 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 multidimensiona l
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.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'�cole, France, +33 (0)1 30 23 00 34
Nov 19 '08 #6
On Nov 19, 9:47*am, James Kanze <james.ka...@gm ail.comwrote:
On Nov 19, 10:12 am, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
wrote:
On Nov 19, 2:14 am, Slain <Slai...@gmail. comwrote:
I need to convert a an array to a multidimensiona l 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. Multidimensiona l arrays in
C++ are stored as one-dimensional arrays anyway.

That's only true in the most superficial sense. *You can't
access a multidimensiona l 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 multidimensiona l
arrays. *But it allows arrays of any type, including array
types, and an array of arrays works pretty much like a
multidimensiona l 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++.

--
Max
Nov 19 '08 #7
On Nov 19, 5:22*am, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
wrote:
On Nov 19, 9:47*am, James Kanze <james.ka...@gm ail.comwrote:


On Nov 19, 10:12 am, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
wrote:
On Nov 19, 2:14 am, Slain <Slai...@gmail. comwrote:
I need to convert a an array to a multidimensiona l 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. Multidimensiona l arrays in
C++ are stored as one-dimensional arrays anyway.
That's only true in the most superficial sense. *You can't
access a multidimensiona l 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 multidimensiona l
arrays. *But it allows arrays of any type, including array
types, and an array of arrays works pretty much like a
multidimensiona l 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++.

--
Max- Hide quoted text -

- Show quoted text -
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
Nov 19 '08 #8
On Nov 19, 11:22 am, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
wrote:
On Nov 19, 9:47 am, James Kanze <james.ka...@gm ail.comwrote:
On Nov 19, 10:12 am, Maxim Yegorushkin
<maxim.yegorush ...@gmail.comwr ote:
On Nov 19, 2:14 am, Slain <Slai...@gmail. comwrote:
I need to convert a an array to a multidimensiona l 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. Multidimensiona l arrays
in C++ are stored as one-dimensional arrays anyway.
That's only true in the most superficial sense. You can't
access a multidimensiona l 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 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.
(Formally speaking, of course, C++ doesn't have
multidimensiona l arrays. But it allows arrays of any type,
including array types, and an array of arrays works pretty
much like a multidimensiona l array for most things.)
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.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Nov 20 '08 #9
On Nov 20, 8:43*am, James Kanze <james.ka...@gm ail.comwrote:
On Nov 19, 11:22 am, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
wrote:
On Nov 19, 9:47 am, James Kanze <james.ka...@gm ail.comwrote:
On Nov 19, 10:12 am, Maxim Yegorushkin
<maxim.yegorush ...@gmail.comwr ote:
On Nov 19, 2:14 am, Slain <Slai...@gmail. comwrote:
I need to convert a an array to a multidimensiona l 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. Multidimensiona l arrays
in C++ are stored as one-dimensional arrays anyway.
That's only true in the most superficial sense. *You can't
access a multidimensiona l 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.
(Formally speaking, of course, C++ doesn't have
multidimensiona l arrays. *But it allows arrays of any type,
including array types, and an array of arrays works pretty
much like a multidimensiona l array for most things.)
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.
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.
Using language constructs one can view that block as a
one-dimensional or multi-dimensional array.

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 underspecificat ion or inconsistency of the standard.

--
Max
Nov 20 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2452
by: M.Siler | last post by:
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT> <!-- var factor_val = new Array(8,7) factor_val = 68.8 factor_val = 55
13
2523
by: Kevin | last post by:
Help! Why are none of these valid? var arrayName = new Array(); arrayName = new Array('alpha_val', 1); arrayName = ; I'm creating/writing the array on the server side from Perl, but I
9
2312
by: Luke Wu | last post by:
Hello, I'm having some problems understanding 2 dimensional arrays. My problem relates to the following code: #include <stdio.h> #define M 3 #define N 3
1
8263
by: Mark Smith | last post by:
I'm trying to copy data from a 1D array to a 2D array. The obvious thing doesn't work: int twoDee = new int; int oneDee = new int { 1, 2 }; Array.Copy(oneDee, 2, twoDee, 2, 2); This causes a RankException. But the MSDN documentation says: When copying between multidimensional arrays, the array
3
8193
by: Claire | last post by:
I have a multidimensional array defined as private double myArray = new double; The first column of the array contains X values, the other contains Y values I have a charting function defined as Add(Array XValues, Array YValues) How do I call the Add function, passing my array columns please. thanks
2
12828
by: chris | last post by:
Hi there, I created a Multidimensional array of labels Label lblMultiArray = new Label { {Label3, LblThuTotal}, {Label4,LblFriTotal} }; Now I would like to compare the values in the array, comparing the text in Label3 and LblThuTotal and the text in Label4 and LblFriTotal.
24
1951
by: Kavya | last post by:
int main (){ int a={{1,2,3},{4,5,6}}; int (*ptr)=a; /* This should be fine and give 3 as output*/ printf("%d\n",(*ptr)); ++ptr;
13
2550
by: Karl Groves | last post by:
I'm missing something very obvious, but it is getting late and I've stared at it too long. TIA for responses I am writing a basic function (listed at the bottom of this post) that returns data from a query into an array. The intent is that the following code:
5
2318
by: LittleCake | last post by:
Hi All, I have a multidimensional array where each sub-array contains just two entries, which indicates a relationship between those two entries. for example the first sub-array: =Array ( =30 =31 )
0
8623
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9187
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8936
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8894
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7776
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6540
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4390
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2360
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.