Subscribe to Bodom's Universe        RSS Feed
-----

Dynamic Allocation... I love it!

Icon Leave Comment
So recently in the forums I have been giving out info on Dynamic Allocation (whether i am asked or not)

This little tidbit of C++, Java, C#, etc is one of my favorite things in the world, and it's beginning to pop up everywhere.
Especially now that I am starting to get into C# .NET programming.

But hey, I love it!

For all of you who don't "get it", let me explain.

The most useful thing for dynamic allocation is declaring multidimentional arrays.

For example, say I want a 2-D array, but I don't know how big it needs to be.

I could just declare it normally:
int Array[20][20];



Thats good and all, but what's the point of having all of them extra boxes?
What if I could size the array on the fly?

Dynamic Allocation saves the day!

Say I want a 2-D array, but I only need an 8 by 8 box.
Declaring an array that's 20x20 would technically work, but thats 20^2 - 8^2 = 336 boxes unused!
Talk about a bigger waste of space than Rosie O'donald!

oh Yes. I went there.

Let us instead, declare what I like to call a DOUBLE POINTER!!! (remember pointers, kids?)
This is not a technical term, just something I've been throwin around the dorm room.
(Which is why I am the only one who knows it, as I have a single)

so we can get a 2-D array like this:

int MaxRow; //Number of Rows
int MaxCol;  // Number of Columns
int **Array; //DOUBLE POINTER!!!!

MaxRow = 8; // Of course, this can be read
					// in from a file or from cin...
MaxCol = 8;  // Same with this. :P

Array = int*[MaxRow] //Notice the * between
								 // int and [, we want this
								 // to be an array of POINTERS!!!!

//WE can then use a for loop to allocate the other columns
//One thing i didn't mention was that all these pointers in our
//array can be allocated to different sizes.
//Thus, we have a very DYNAMIC way to read in and store data!
for(int i = 0; i < MaxRow; i++)
	Array = new int[MaxCol]  //No * here!

//we can then fill it with numbers, and access it as if it were
//a normal 2-D array.



Not so bad eh?

Also, notice my capitalization in all the variables. C# will do that to you :P

Hope you enjoyed this, and MAYBE learned something?

Peace out
~Bodom

0 Comments On This Entry

 

January 2022

S M T W T F S
      1
2345678
9101112131415
161718192021 22
23242526272829
3031     

Recent Comments

Search My Blog

16 user(s) viewing

16 Guests
0 member(s)
0 anonymous member(s)