Skip to main content
GameDev.net gamedev.net
🔒 Locked

Allocating multidimensional arrays

Started by Abob May 22, 2002 at 2:46 PM 50 replies 850+ views
Original Post
Abob
Abob
Is there a way to directly allocate a multidimensional array using new? This is the way I have been doing it.
    


int main()
{
int i;


int **TheArray;
TheArray = new int*[10];
for (i = 0; i < 10; i++)
{
TheArray[i] = new int[10];
}
//

//

//

//

for (i = 0; i < 10; i++)
{
delete[] TheArray[i];
}
delete[] TheArray;

return 0;

}
    
Thanks for any help. [edited by - Abob on May 22, 2002 3:47:58 PM]
Arrg!!
Fruny
Fruny
Yeah, that works. I''d use a vector of vectors though.


  
#include <vector>
using std::vector;

void main()
{
// temporary to make initialisation easier

// create a vector of 10 ints

// (vector of 10 elements, initialised with int() (i.e. 0))

vector< int > tmp( 10 );

// create a vector of 10 vectors of 10 ints

// (vector of 10 elements, initialised with tmp)

vector< vector<int> > vec(10, tmp)

// no delete required.

}


Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
foofightr
foofightr
I ran ito this problem a few years ago, let''s see if I can remember.

If you have a rather large multi-dimensional array, the problem is that it might get segmented after a lot of memory allocations, which is not necessarily a bad thing (depending on the application), but having it all in consecutive memory would be best.


  
int **array;
int *data;

array = new int*[1000];
data = new int[1000 * 3000];

for (i=0 ; i<1000 ; i++)
array[i] = &data[i * 3000];



If any syntax is slightly off I''m sorry. But that is the general idea.

Vasialek
Vasialek
If u are going to use "equal" array, which contains the same amout of elements in each row, it will be better to create a class for handling it.
It is allocating single memory block, & then imitate spliting into rows. I think it is more simple

#include <stdio.h>
#include <string.h> // memset()

class LnMDim{
public:
LnMDim( int rows, int cols );
~LnMDim();
void Set( int value, int row, int col );
int Get( int row, int col );
private:
int* GetPointer( int row, int col );
int *p, totalRows, totalCols;
};

//---------------------------------------------------------------

int main( int argc, char *argv[] ){
int rows = 12, cols = 40;
LnMDim obj( rows, cols );
for( int j = 1; j < rows; j++ ){
for( int i = 1; i < cols; i++ ){
obj.Set( i, j, i );
}
} // END FOR
for( int j = 1; j < rows; j++ ){
for( int i = 1; i < cols; i++ ){
printf(" %d", obj.Get( j, i ) );
}
printf("\n");
} // END FOR
printf("\t( 3, 5 ) = %d\n", obj.Get( 3, 5 ) );
obj.Set( 7, 3, 5 );
printf("\t( 3, 5 ) = %d\n", obj.Get( 3, 5 ) );
return 0;
}

//---------------------------------------------------------------
LnMDim::LnMDim( int rows, int cols ){
p = new int[rows*cols];
if( !p ){
totalRows = totalCols = 0;
return;
}
memset( p, sizeof( p ), 0 );
totalRows = rows;
totalCols = cols;
}
//---------------------------------------------------------------
LnMDim::~LnMDim(){
if( p ){
delete []p;
}
}
//---------------------------------------------------------------
void LnMDim::Set( int value, int row, int col ){
int *localP = GetPointer( row, col );
if( localP ){
*localP = value;
}
return;
}
//---------------------------------------------------------------
int LnMDim::Get( int row, int col ){
int *localP = GetPointer( row, col );
if( localP ){
return *localP;
}
return 0;
}
//---------------------------------------------------------------
int* LnMDim::GetPointer( int row, int col ){
if( ( row < 0 ) || ( row > totalRows ) || ( col < 0 ) || ( col > totalCols ) ){
return NULL;
}
int offset = totalCols * ( row - 1 ) + col - 1;
// printf("\tGetPointer(): %d, %d = %d\n", row, col, offset );
return p + offset;
}
//---------------------------------------------------------------
foofightr
foofightr
And people say C++ complicates code for nothing!
Beer Hunter
Beer Hunter
foofightr has the right idea. I''ve been using that myself
a person
a person

  
// alloc

int *multi = new[width*height];

// access

multi[x+y*width];

// free

delete [] multi;

simple ne?
great if each row is the same length, else you should do it how you have otherwise you will waste ram depending on how much different the size of the rows are.

foofighters method is interesting, but this way is much more streamline and relieves you of having to deal with two arrays. you could use a single vector as well.

Beer Hunter
Beer Hunter
But now you have to explicitly multiply by the width all the time. I''d rather use two sets of square brackets.
foofightr
foofightr
Ok this is a rant. Not specifically related to this thread but here goes..

It bugs me when people ask questions and get an answer of "use the C++ library < vector>" or whatever. The C++ library is all well and good, it saves time, bugs, and all the good stuff. But it doesn''t teach shit and you know it. It simplifies everything to the point that you can''t learn anything by using it. I see many people give these answers, and it saddens me.

Do you teach a 4th grader how to divide by handing him a calculator and saying "here use this, it''s simple and it works"? I sure hope not. You have to learn HOW to divide before you should use a calculator, because it''s just there to save time and mistakes, not to teach you. What if you lose your calculator a few years later and don''t know how to divide? Wouldn''t that just suck?

Anyway, I''m all for C++ but it''s just not a good way to teach people programming concepts. That''s why I always use C code when answering questions, because it''s more in tune to the actual concept(s) I''m trying to explain. I could have explained 3d or even 4d array allocation but he didn''t ask. My code would have been a good 10-15 lines long, but it would have shown what I was trying to explain more than some nested vectors. Know what I mean?


p.s. I know the guy was asking mostly about 2d array syntax , but in general it bugs me when people give answers "the C++ way" to people who are asking about concepts.
Vasialek
Vasialek
I''m O.K. for dividing without calculator, I''ll be suprised if Foofightr is from West europe or USA
But if u want to use C, use malloc() & free(). New & delete is more C++ features.
Also, I see nothing bad in hiding all details under classes. I prefer to create class myself, but then I''d like to use it more simple - call 1 function ( obj.Get( 1, 7 ) ), then checking for bounds & calculating offset.
For sure, for simplicity, u could write just 5 lines, but may be it is good to understand how it should be?!

Lekha
Kippesoep
Kippesoep
quote:
Original post by Beer Hunter
But now you have to explicitly multiply by the width all the time. I''d rather use two sets of square brackets.


Take a look at the template class I have posted in this thread for an easy way to do that.

Kippesoep
SabreMan
SabreMan
quote:
Original post by foofightr
It bugs me when people ask questions and get an answer of "use the C++ library < vector>" or whatever. The C++ library is all well and good, it saves time, bugs, and all the good stuff. But it doesn''t teach shit and you know it. It simplifies everything to the point that you can''t learn anything by using it. I see many people give these answers, and it saddens me.

Excellently said, but I don''t think you go far enough. There should be a "real programmers" degree where programmers have to grow their own silicon ingot and etch their own processor, followed by toggling bits into a Von Neumann machine, eventually moving onto machine language. Only when those stages have been carried out should they progress through the various generations of programming language, eventually arriving at the heady wonders of Visual Basic, probably just skipping C++ as it''s more trouble than it''s worth. Certainly, if someone wants to learn to actually do something with a programming language, a course such as this should be sufficient to stifle their ideas for a good 10 years or so. These people so often get ideas above their station.

Allocate a multidimensional array indeed! You don''t even know about transistor circuits yet!


[ C++ FAQ Lite | ACCU | Boost | Python | Agile Manifesto! ]
Beer Hunter
Beer Hunter
Kippesoep - I don''t know how I overlooked that, considering I''ve already got a template for the other method. I guess I''ll compare them for performance next time I get bored

SabreMan - Every step further you take it, the more the student will learn, but the more time is needed. Clearly, there will come a point where it is no longer worth going any further, since the time would be better spent actually programming. The only question is, where is that point?
foofightr
foofightr
Sabre, either you have some reading comprehension problems... or as I pointed out in another thread, you just love to assert yourself as god's gift to software engineering.

Get over yourself already. You know stuff. Probably a lot of stuff. But does that mean you always know how to apply your knowledge effectively? Not necessarily.

At any rate, this line of discussion isn't very productive, so I'm pretty much done with this thread. I'm sure you love having the last word, so be my guest.

[edited by - foofightr on May 24, 2002 7:36:13 AM]
SabreMan
SabreMan
quote:
Original post by foofightr
At any rate, this line of discussion isn''t very productive, so I''m pretty much done with this thread. I''m sure you love having the last word, so be my guest.

Why, thankyou. The point I was trying to make is that you don''t have to know how something works to be able to use it. That is idle conjecture, and a conjecture that I disagree with.

While I''m at it, all these things that you continually accuse me of and flame me about are not actually going on in my head, as you seem to think. You are simply seeing something that is not there. So, I''d be grateful if you stopped telling me what I love to do and how I think about myself. I''m fully capable of realising those things without your help.


[ C++ FAQ Lite | ACCU | Boost | Python | Agile Manifesto! ]
Kippesoep
Kippesoep
Of course you don''t have to know how something works in order to use it. I don''t think there''s anyone who knows exactly how OpenGL, DirectX, Win32, all the drivers, the STL, the standard C library etc work. It does make sense to learn a bit about what goes on behind the scenes because that helps in order to make efficient use of libraries.

Personally, I think putting together something like a linked list class is very useful from a learning point of view. Once you''ve done it, though, throw it away and use the STL...

Kippesoep
SabreMan
SabreMan
quote:
Original post by Kippesoep
Personally, I think putting together something like a linked list class is very useful from a learning point of view. Once you''ve done it, though, throw it away and use the STL...

Well, not wishing to invoke the spectre of the dreaded linked-list argument , I pretty much agree with what you''ve said However, there are two particular points that change the overall approach. Firstly, when a job needs to be done, it is more useful to know when and why to use these things than how they actually work. Secondly, if you never need to know how they work, why should you spend time learning them? Learn them when you have a need to know, I say. By throwing up obstacles such as "you must learn pointers before programming in C++" or "you must know how linked-lists work before using them", you are making C++ less accessible to the majority of people. The techniques I advocate are supposed to make it more accessible.


[ C++ FAQ Lite | ACCU | Boost | Python | Agile Manifesto! ]
Extrarius
Extrarius
While knowing how something works is not required to use it, that knowledge helps the user to use it effeciently where it is best fit to the job. For example, using an stl::map with an integer key as one would use a standard static array is very inefficient, and using an stl::vector or some other construct might be more usefull if a static array is not an option.

"The Requested Information Is Unknown Or Classified" -Anonymous
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
SabreMan
SabreMan
That only really requires one to understand the properties of a map and an array - it doesn''t mean you have to have created your own map class to understand when and how to use it. If you were to extend the argument, then you could say that you need to implement the features in the C++ compiler, such as the runtime despatch mechanism, in a language like C before you should be allowed to use them in C++. If you agree that there is something wrong with that argument, perhaps you can then start to see the logic behind things like learning to use vectors before arrays or smart pointers before pointers. In both of those cases, the C++ library facility is actually a generalisation of the C concept. It makes sense to approach problems from the general approach, and specialise as you need to do so.


[ C++ FAQ Lite | ACCU | Boost | Python | Agile Manifesto! ]
Beer Hunter
Beer Hunter
The fastest way to understand a small thing may be to implement it. This is not true for large things.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.