473,785 Members | 3,388 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Initializing multi-dimensional array in constructor

I'm having a ton of trouble initializing a multi-dimensional array
inside a constructor, largely because I don't know the size of the
array until runtime. I have a class that looks like this:

class MyClass
{
public:
const int size;
MyClass( const int );
};

MyClass::MyClas s( const int s )
: size( s )
{
int (*arrayPtr)[size][size] = new int[size][size][size];
}

When I compile this with g++ (actually, Apple's version of g++, in case
that matters), I get the following error:
myclass.cpp : In constructor 'MyClass::MyCla ss(int)':
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression

Can anyone explain why I'm getting this error message, especially since
size is declared const, and also can anyone help me out with what to do
about it? Thanks.

--Jay

Jul 24 '06 #1
4 4406
ja*******@gmail .com wrote:
I'm having a ton of trouble initializing a multi-dimensional array
inside a constructor, largely because I don't know the size of the
array until runtime. I have a class that looks like this:

class MyClass
{
public:
const int size;
MyClass( const int );
};

MyClass::MyClas s( const int s )
: size( s )
{
int (*arrayPtr)[size][size] = new int[size][size][size];
}

When I compile this with g++ (actually, Apple's version of g++, in
case that matters), I get the following error:
myclass.cpp : In constructor 'MyClass::MyCla ss(int)':
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression

Can anyone explain why I'm getting this error message, especially
since size is declared const, and also can anyone help me out with
what to do about it? Thanks.
Please see the FAQ. Creation of multidimensiona l dynamic arrays is
actually covered in it.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 24 '06 #2
Jay Harris posted:

int (*arrayPtr)[size][size] = new int[size][size][size];

You're going to need to employ more devious tactics, something like:

(I've written this hastily in the last half hour, so expect bugs.)
#include <cassert>

template<class T>
class Accessor2D {
protected:

T *const p;
unsigned const d2;

public:

Accessor2D(T *const parg,unsigned const arg2) : p(parg), d2(arg2)
{
assert(parg);
assert(arg2);
}

T *operator[](unsigned const arg2)
{
assert(arg2);

return p + (arg2 * d2);
}
};
template<class T>
class Accessor3D {
protected:

T *const p;
unsigned const d2;
unsigned const d3;

public:

Accessor3D(T *const parg,unsigned const arg2, unsigned const arg3)
: p(parg), d2(arg2), d3(arg3)
{
assert(parg);
assert(arg2);
assert(arg3);
}
Accessor2D<Tope rator[](unsigned const arg1)
{
assert(arg1);

return Accessor2D<T>( p + (arg1 * d2 * d3), d3 );
}
};
/* Now here comes your class */
class MyClass {
public:
unsigned const size;
MyClass(unsigne d const);
};

MyClass::MyClas s(unsigned const s) : size(s)
{
Accessor3D<inta rr(new int[size*size*size],size,size);

arr[0][0][0] = 5;

arr[0][1][2] = 7;
}

int main()
{
MyClass obj(7);
}

--

Frederick Gotham
Jul 24 '06 #3
ja*******@gmail .com wrote:
I'm having a ton of trouble initializing a multi-dimensional array
inside a constructor, largely because I don't know the size of the
array until runtime. I have a class that looks like this:
"Size" portion of array types in C++ must be a so called 'integral constant
expression' (ICE). The exact definition of ICE can be found in the language
specification, but the idea is that the size must be known at compile time.
Non-static class data members cannot be used in ICEs. This is what makes the
compiler to complain.

Since in your case array sizes are only known at run-time, there's no way to
achieve what you want with array type or type derived from array type (as the
'int (*)[size][size]' you are trying to use). There are different ways to solve
the problem:

1. Use a 1D array of size 'size * size * size' and simulate a 3D access by
manually transforming the 3D indices into the corresponding the 1D index:

[x][y][z] - [x * size * size + y * size + z]

(that's, BTW, how built-in arrays work in C/C++)

2. Use the well-known array-of-pointers idiom:

int*** arrayPtr = new int**[size];
// Then for each i
arrayPtr[i] = new int*[size];
// Then for each i, j
arrayPtr[i][j] = new int[size];

(the above is just an illustration of the idea; the actual implementation can be
done in a neater way).

3. (Might make the most sense out of three) Use
'std::vector<st d::vector<std:: vector<int >'.
class MyClass
{
public:
const int size;
MyClass( const int );
};

MyClass::MyClas s( const int s )
: size( s )
{
int (*arrayPtr)[size][size] = new int[size][size][size];
}

When I compile this with g++ (actually, Apple's version of g++, in case
that matters), I get the following error:
myclass.cpp : In constructor 'MyClass::MyCla ss(int)':
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression
--
Best regards,
Andrey Tarasevich
Jul 24 '06 #4
Thanks. Option 1 seemed the simplest, so I went with it.

Andrey Tarasevich wrote:
ja*******@gmail .com wrote:
I'm having a ton of trouble initializing a multi-dimensional array
inside a constructor, largely because I don't know the size of the
array until runtime. I have a class that looks like this:

"Size" portion of array types in C++ must be a so called 'integral constant
expression' (ICE). The exact definition of ICE can be found in the language
specification, but the idea is that the size must be known at compile time.
Non-static class data members cannot be used in ICEs. This is what makes the
compiler to complain.

Since in your case array sizes are only known at run-time, there's no way to
achieve what you want with array type or type derived from array type (as the
'int (*)[size][size]' you are trying to use). There are different ways to solve
the problem:

1. Use a 1D array of size 'size * size * size' and simulate a 3D access by
manually transforming the 3D indices into the corresponding the 1D index:

[x][y][z] - [x * size * size + y * size + z]

(that's, BTW, how built-in arrays work in C/C++)

2. Use the well-known array-of-pointers idiom:

int*** arrayPtr = new int**[size];
// Then for each i
arrayPtr[i] = new int*[size];
// Then for each i, j
arrayPtr[i][j] = new int[size];

(the above is just an illustration of the idea; the actual implementation can be
done in a neater way).

3. (Might make the most sense out of three) Use
'std::vector<st d::vector<std:: vector<int >'.
class MyClass
{
public:
const int size;
MyClass( const int );
};

MyClass::MyClas s( const int s )
: size( s )
{
int (*arrayPtr)[size][size] = new int[size][size][size];
}

When I compile this with g++ (actually, Apple's version of g++, in case
that matters), I get the following error:
myclass.cpp : In constructor 'MyClass::MyCla ss(int)':
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression

--
Best regards,
Andrey Tarasevich
Jul 26 '06 #5

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

Similar topics

50
6382
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong def foo(self, data): self.attr1=data self.attr2.append(data) The initialization of attr1 is obviously OK, all instances of Father redefine it in the method foo. But the initialization of attr2 is wrong
14
10650
by: Avi Uziel | last post by:
Hi All, I'm writing a Windows DLL which contain some utility classes. One of my classes is Singleton, therefore contain some static members. I'm using VC6 and linking to the DLL statically. My question is where is the correct (and best way) to initialize theses variables? If I initialize them in the class CPP (in the DLL) then I get linkage error when I try to link my project with the LIB, and I don't want to make the user initialize...
12
3880
by: * ProteanThread * | last post by:
but depends upon the clique: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=954drf%24oca%241%40agate.berkeley.edu&rnum=2&prev=/groups%3Fq%3D%2522cross%2Bposting%2Bversus%2Bmulti%2Bposting%2522%26ie%3DUTF-8%26oe%3DUTF-8%26hl%3Den ...
6
8183
by: cody | last post by:
What are multi file assemblies good for? What are the advantages of using multiple assemblies (A.DLL+B.DLL) vs. a single multi file assembly (A.DLL+A.NETMODULE)?
4
17878
by: mimmo | last post by:
Hi! I should convert the accented letters of a string in the correspondent letters not accented. But when I compile with -Wall it give me: warning: multi-character character constant Do the problem is the charset? How I can avoid this warning? But the worst thing isn't the warning, but that the program doesn't work! The program execute all other operations well, but it don't print the converted letters: for example, in the string...
5
5768
by: bobwansink | last post by:
Hi, I'm relatively new to programming and I would like to create a C++ multi user program. It's for a project for school. This means I will have to write a paper about the theory too. Does anyone know a good place to start looking for some theory on the subject of multi user applications? I know only bits and pieces, like about transactions, but a compendium of possible approches to multi user programming would be very appreciated!
8
7519
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine, like this: for(var i=0; i<list; i++) { var name = list; }
0
2329
by: Sabri.Pllana | last post by:
We apologize if you receive multiple copies of this call for papers. *********************************************************************** 2008 International Workshop on Multi-Core Computing Systems (MuCoCoS'08) Barcelona, Spain, March 4 - 7, 2008; in conjunction with CISIS'08. <http://www.par.univie.ac.at/~pllana/mucocos08> *********************************************************************** Context
1
9319
by: mknoll217 | last post by:
I am recieving this error from my code: The multi-part identifier "PAR.UniqueID" could not be bound. The multi-part identifier "Salary.UniqueID" could not be bound. The multi-part identifier "PAR.UniqueID" could not be bound. The multi-part identifier "PAR.PAR_Status" could not be bound. The multi-part identifier "Salary.New_Salary" could not be bound. The multi-part identifier "Salary.UniqueID" could not be bound. The multi-part...
38
2231
by: junky_fellow | last post by:
Guys, I was just looking at some code where to initialize an integer with all F's following statement is used; unsigned int i = -1; I want to know if this is the right way of doing the things ? if not, what is the correct way to do this ?
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10319
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...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10087
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
9947
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...
1
7496
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.