Re: 2d array with comma operator in C++?
Diaboflo wrote:
On Feb 20, 6:22 am, "Ivan Novick" <ivan.d.nov...@gmail.com> wrote:
On Feb 19, 10:39 am, "Diaboflo" <flohudel...@web.de> wrote:
I have seen many threads that you can't innitialise 2d arrays with a
comma operator in C++. But when I tried it it actually worked fine. I
can call any element of the array using the comma operator.
I'm using g++ on a sun station.
Are there important reasons why I shouldn't do it this way and better
allocate it as a **pointer?
{ What you wrote as [a,b] below is actually equivalent to [b]. -mod/sk }
int main()
{
double *e;
e=new double[10,10];
e[8,8]=1234567;
e[1,7] = 17;
e[7,1] = 71;
cout << e[8,8]<<endl;
cout << e[1,7]<<endl;
cout << e[7,1]<<endl;
return 0;
}
Just in case the previous posters replys were not clear enough:
1) new double[10,10] does NOT allocate a 2-d array but a 1-d array of
10 elements
2) e[8,8] does NOT reference the 8,8 element in a 2-d array but the 8
element in a 1-d array.
3) The correct way to dynamically allocate a 2-D array is new
double[10][10]
4) The correct way to access the 8,8 element in a 2-D array is e[8][8]
Now heres an interesting question, if you allocate a 2-D array like
this:
double (*array)[5] = new double[3][5];
How do you delete that?
When I try to dynamically allocate a 2d array with
new double[10][10] I get following errormessage:
array.cpp: In function `int main()':
array.cpp:34: cannot convert `double (*)[10]' to `double*' in
assignment
Look at what Ivan wrote (or my own response to your initial
posting). Obviously, if you violate the type system, you're
going to get compiler errors. When you allocate an array with
new, new returns a pointer to the first element, and the type of
that pointer is pointer to the element type. Since a two
dimensional array is in fact an array of arrays, the first
element is an array, and that's what new returns a pointer to.
I found following thread which describes how to allocate a 2d array:
http://www.codeguru.com/forum/showthread.php?t=373065
It's an alterative solution, which allows for both dimensions to
be variables. Usually, it will result in somewhat slower code,
because of a loss of locality (but a lot depends---it avoids a
multiplication, which on a lot of older machines is a slow
operation).
As I suggested in my posting, the best solution is a user
defined class, to wrap the implementation details. In addition
to ensuring that you only have to write the array allocation
code once (and thus debug it once), it allows easily changing
the implementation, using either a single array of n*m elements,
and multiplication, or an array of pointers.
--
James Kanze (GABI Software) email:james.kanze@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
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]