Filling a dynamic array with objects (C++)

Started by
8 comments, last by visitor 14 years, 2 months ago
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 = 0;
     }
}

void main() {
     Simulate(5);
}

How would I accomplish this (inserting objects instead of ints)?
Advertisement
std::vector<Ball> balls(len);
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 = 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.)
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!
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.
Uziel was defeated by Tiny Mandragora.
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.
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).
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 <=.
Fate fell short this time your smile fades in the summer.
Also, array indices start at 0

for ( int i = 0; i < len; i ++ )
array = 0;<br><br>
If you must allocate it yourself, then for zeroing the array, there's also:

int* array = new int[length]();

This topic is closed to new replies.

Advertisement