Hi,
I have a vector of pointers to objects, I need to pass this into a third party function which is expecting an array of objects, the function prototype goes like this:
void func(int *data, int size);
Which updates everything in data.
Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <stdio.h>
#include <vector>
void func(int *data, int size);
int main()
{
std::vector <int*> things;
int a[10];
for(int i = 0; i < 10; i++)
{
int *d = new int;
*d = i + 100;
things.push_back(d);
a[i] = i + 100;
}
func(things[0], 10);
printf("\n");
func(a, 10);
}
void func(int *data, int size)
{
//in real world this function does something to modify the data
for(int i = 0; i < size; i++)
{
printf("%d\n", data[i]);
}
}
| |
You'll see I've tried passing an array (a) to func which shows the correct output. The output is:
100
-33686019
98893109
-2013260835
18001016
17987184
1540103372
556
4
2
100
101
102
103
104
105
106
107
108
109
|
My question is why doesn't func produce the expected output when passing in my vector of pointers? It appears to handle the first item correctly but then it all goes wrong. I thought vectors stored data like an array (the next item immediately after the previous). How do I put this right?
-------------------------------------------------------------------------------
Bit of background:
I'm using a vector of pointers as I have a base class (gameObject) and a few derived classes (enemy, player, etc) so I can have a single list of all objects and call methods at certain times (e.g update function for each object etc) and I can add and remove new gameObjects when I like. In my example int* is just a replacement for gameObject*.
Any thoughts or feedback appreciated.
Thanks!