470,833 Members | 1,631 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,833 developers. It's quick & easy.

class with two dimensional array as a member (I need help)


I'd like to have a two dimensional array as a member of a class, bu if
I did it in the following way:

class A {
const int n;
int a[n][n];
A(int nn): n(nn) {};
~A() {};

this produce error, when I changed it to:

class A {
const int n;
int** a;
A(int nn): n(nn) {
for (int i=0;i<n;i++)
a[i]=new int[n];
~A() {
for (int i=0;i<n;i++)
delete [] a[i];

it works fine, however when I tried to use it in some program like

int main() {
int x,y;
A a(10);
return 0;

program compiled without any problems, but when I run it it was thrown
an unknown exception ... I don't understand what is going on.
Jun 27 '08 #1
1 1009
On May 13, 9:18 am, "Alf P. Steinbach" <al...@start.nowrote:
* Pawel_Iks:
Just a couple of nits (and the correction of a typo), but...
class A
size_t myN;
std::vector<int myElements;

size_t indexFor( size_t i, size_t j ) const
return myN*i + j;
A( size_t n ): myN( n ), myElements( n*n ) {}
int at( size_t i, size_t j ) const
return myElements.at( indexFor( i + j ) );
You certainly meant "indexFor( i, j )". As written, it won't
compile (and wouldn't do the right thing if it did).

Also, I very much question the wisdom of using at() here. If
there's an error in the indexing, you want an assertion failure,
not an exception. Which is what you'll get with any reasonable
implementation of std::vector<>::operator[]. But of course,
even that is only partially right, since something like 20, 0
will pass even if myN is 10. You really need to use assert in
indexFor, i.e.:

size_t indexFor( size_t i, size_t j ) const
assert( i < myN && j < myN ) ;
return myN*i + j;

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

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by KellyH | last post: by
2 posts views Thread by DevarajA | last post: by
3 posts views Thread by Bryan Ruddy via .NET 247 | last post: by
272 posts views Thread by Peter Olcott | last post: by
15 posts views Thread by Eric Lilja | last post: by
4 posts views Thread by Gernot Frisch | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.