Reputation: 589
I am trying to write a pointer array to structs in C++. My main goal is to be able to dynamically add pointers to the array. I am having trouble with the synthax
struct items
{
int member1;
int member2;
};
int N=5;
items **ptr=new item *[N]; // This is a ptr to an array of ptr's. Each ptr
// in this array needs to point to an items struct.
My question is how to write in the struct's objects from this point on. I know I need to create them first but I don't have any idea how to do that.
Upvotes: 1
Views: 6004
Reputation: 1
You're allocating only an array of pointers of item *
, you'll need to allocate the memory for each item
also, e.g.:
struct item // naming it 'items' might be confusing, and was used inconsistently
// in your code sample
{
int member1;
int member2;
};
int N=5;
item **ptr=new item *[N];
for(int i = 0; i < N; ++i)
{
ptr[i] = new item();
}
Accessing your structure members looks like this:
ptr[2]->member1 = 42; // Sets member1 of the 3rd item element to 42
Note that you'll need to free the allocated memory somewhere as follows:
for(int i = 0; i < N; ++i)
{
delete ptr[i];
}
delete [] ptr;
I general for c++ you'd be better off using a c++ standard container like:
#include <vector>
int N = 5;
std::vector<item> myItems;
myItems.resize(N,item());
myItems[2].member1 = 42; // Sets member1 of the 3rd item element to 42
which would do all the memory management for you internally.
If you're using c++11 and do not need dynamically sized arrays you can even avoid heap allocated memory at all using std::array
:
#include <array>
std::array<item,5> myItems; // Size is fixed to 5, you can't use a variable here
myItems[2].member1 = 42; // Sets member1 of the 3rd item element to 42
Upvotes: 3
Reputation: 2620
Firstly you have to finish the allocation step.
for(int i=0;i<N;i++)
ptr[i]=new items;
Then you can access the array using e.g.:
ptr[0]->member1=123;
Upvotes: 0
Reputation: 406
You can add objects to your array by ptr[i] = new items()
. And you can access data in items** ptr
by ptr[i]->member1
. But I'll strongly recommend using stl containers and smart pointers.
Upvotes: 1