Jump to content

  • Log In with Google      Sign In   
  • Create Account


Filling a dynamic array with objects (C++)


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
9 replies to this topic

#1 Novark   Members   -  Reputation: 133

Like
0Likes
Like

Posted 06 February 2010 - 03:14 PM

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)?

Sponsor:

#2 e‍dd   Members   -  Reputation: 2105

Like
0Likes
Like

Posted 06 February 2010 - 03:44 PM


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


#3 scgames   Members   -  Reputation: 1969

Like
0Likes
Like

Posted 06 February 2010 - 03:49 PM

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.)


#4 Novark   Members   -  Reputation: 133

Like
0Likes
Like

Posted 06 February 2010 - 04:01 PM

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!

#5 Uziel2101   Members   -  Reputation: 165

Like
0Likes
Like

Posted 06 February 2010 - 04:03 PM

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.

#6 Novark   Members   -  Reputation: 133

Like
0Likes
Like

Posted 06 February 2010 - 04:21 PM

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.

#7 scgames   Members   -  Reputation: 1969

Like
0Likes
Like

Posted 06 February 2010 - 04:24 PM

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).

#8 BrickInTheWall   Members   -  Reputation: 150

Like
0Likes
Like

Posted 06 February 2010 - 09:54 PM

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 <=.

#9 GregMichael   Members   -  Reputation: 147

Like
0Likes
Like

Posted 06 February 2010 - 09:59 PM

Also, array indices start at 0

for ( int i = 0; i < len; i ++ )
array[ i ] = 0;



#10 visitor   Members   -  Reputation: 643

Like
0Likes
Like

Posted 06 February 2010 - 10:10 PM

If you must allocate it yourself, then for zeroing the array, there's also:


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





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS