Sign in to follow this  
Novark

Filling a dynamic array with objects (C++)

Recommended Posts

Novark    133
I'm trying to make an array of size 'len' and fill it with objects, let's say for example 'Ball'. Edit: Sorry, should have mentioned - C++. Here's an example (filling an array with ints):
void Simulate(int len) {
     int i;
     int *arr = NULL;
     arr = new int[len];

     for (i=1; i<=len; i++) {
          //Fill the array with zeros
          arr[i] = 0;
     }
}

void main() {
     Simulate(5);
}

How would I accomplish this (inserting objects instead of ints)?

Share this post


Link to post
Share on other sites
jyk    2094
This'll all be pretty standard stuff, but here are a few tips. First, your code, cleaned up a bit and with some comments added:

void Simulate(int length) {
// Some C-isms here. In C++ we generally try to declare variables as near
// first use as possible. Also, there's no point in assigning NULL to 'arr' and
// then immediately overwriting it with another value. I would also suggest
// not getting in the habit of dropping one or two letters from variable names
// like that; it doesn't save you many keystrokes (if that even matters), and
// it makes the code harder to read and understand.
///nt i;
//int *arr = NULL;
//arr = new int[length];
int* array = new int[length];

// Note that i is declared as part of the 'for' statement:
for (int i=1; i<= length; i++) {
//Fill the array with zeros
arr[i] = 0;
}

// I know this is just an example, but be aware that you have a memory leak here;
// 'array' goes out of scope at the end of this function, but the block of memory
// it points to is never freed. To clean up properly, you would do this:
// delete [] array;
}

As for your 'for' loop, the C++ standard library provides a convenient function that assigns a single value to every element in a specified range. In this case, you could replace your entire for loop with the following line of code:
std::fill(array, array + length, 0);
As for creating an array of objects of a class or struct type rather than of a built-in type, it depends on a number of things, but the simplest case would look like this:
Ball* array = new Ball[length];
In other words, the same as in your example above.

Once you feel you have a good grasp of how dynamic memory management works in C++, it would be a good idea to look into some of the containers offered by the standard library, such as vector. (Once you've spent some time with these various container classes, the advantages of using them will most likely become self-evident.)

Share this post


Link to post
Share on other sites
Novark    133
Quote:
Original post by the_edd

std::vector<Ball> balls(len);


Thanks, I'll take a look at this.

Quote:
Original post by jyk
This'll all be pretty standard stuff, but here are a few tips. First, your code, cleaned up a bit and with some comments added:

*** Source Snippet Removed ***
As for your 'for' loop, the C++ standard library provides a convenient function that assigns a single value to every element in a specified range. In this case, you could replace your entire for loop with the following line of code:
std::fill(array, array + length, 0);
As for creating an array of objects of a class or struct type rather than of a built-in type, it depends on a number of things, but the simplest case would look like this:
Ball* array = new Ball[length];
In other words, the same as in your example above.

Once you feel you have a good grasp of how dynamic memory management works in C++, it would be a good idea to look into some of the containers offered by the standard library, such as vector. (Once you've spent some time with these various container classes, the advantages of using them will most likely become self-evident.)


Good stuff - Thanks!

Share this post


Link to post
Share on other sites
Uziel2101    242
Also to note along with what jyk has said; your array is going out of bounds and writing into memory it doesn't own. It may work now but at some point it will crash. when you declare an array of size "length" you allowed to access "array[0], array[1] .... all the way to array[length - 1]" anything beyond that the array doesn't own, and can / usually crash.

As for filling an array with 0's I personally go with memset.

Share this post


Link to post
Share on other sites
Novark    133
Quote:
Original post by Uziel2101
Also to note along with what jyk has said; your array is going out of bounds and writing into memory it doesn't own. It may work now but at some point it will crash. when you declare an array of size "length" you allowed to access "array[0], array[1] .... all the way to array[length - 1]" anything beyond that the array doesn't own, and can / usually crash.

As for filling an array with 0's I personally go with memset.


Thanks for the tip - for my purpose, the array will never need to be expanded, so I won't need to worry about writing past the end of the array.

Share this post


Link to post
Share on other sites
jyk    2094
Quote:
Also to note along with what jyk has said; your array is going out of bounds and writing into memory it doesn't own. It may work now but at some point it will crash. when you declare an array of size "length" you allowed to access "array[0], array[1] .... all the way to array[length - 1]" anything beyond that the array doesn't own, and can / usually crash.
Good catch (I didn't even notice that).
Quote:
Thanks for the tip - for my purpose, the array will never need to be expanded, so I won't need to worry about writing past the end of the array.
Just to be clear, you're *already* writing past the end of the array (that's what Uziel2101 was getting at).

Share this post


Link to post
Share on other sites
BrickInTheWall    150
Errm, memory leak alert. You should at least return a pointer to the first element from the function if you plan on using this array, and be sure to call delete[] once you're done with it. As for using it with objects from classes or structs, the syntax is exactly the same, just replace all instances of 'int' with your class/struct name. Also use for (int i = 0; i <len; i++), not <=.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this