Sign in to follow this  
Endemoniada

*Solved* Pointer to Pointer Problem

Recommended Posts

Hi guys, Shouldn't this work: struct Vertex { float x; float y; }; Vertex* v_array=new Vertex[8]; Vertex** v_list=new Vertex*[8]; for(i=0;i<8;i++) v_list[i]=v_array+i; Vertex* v=v_list[2]; Vertex** v_group[4]; v_group[0]=&v; Vertex* v2=*(v_group[0]); v2->x=1.0f; I hope I typed that correctly. [Edited by - Endemoniada on June 9, 2007 10:32:27 AM]

Share this post


Link to post
Share on other sites
I'm not sure if you where just wondering for understanding's sake or if you where actually asking what the best way to achieve that effect is, so if it was the first then yes that is correct and if it was the second here are two of the preferred ways to do something along those lines.


struct Vertex
{
float x;
float y;
};

typedef std::vector<Vertex > vert_list_t;
typedef std::vector<Vertex*> vert_pointer_list_t;

// Create two vectors (arrays) of 8 elements
vert_list_t verts (8);
vert_pointer_list_t vert_pointers(8);

// set the second vector to hold the addresses of the elements in the first vector
std::transform( verts.begin()
, verts.end()
, vert_pointers.begin()
, &boost::address_of
);

Vertex* vert = vert_pointers[2];

typedef std::vector<Vertex**> vert_group_t;

vert_group_t vert_group(4);
vert_group[0] = &vert;

Vertex* vert_2 = *v_group[0];
vert_2->x = 1.0f;



Or if the arrays of pointers will only ever hold pointers into the first array then this is preferable


struct Vertex
{
float x;
float y;
};

typedef std::vector<Vertex > vert_list_t;
typedef std::vector<vert_list_t::iterator> vert_iter_list_t;

// Create a vector of 8 elements and another vector which will store
// iterators into the first vector
vert_list_t verts(8);
vert_iter_list_t vert_iters;

// fill the second vector with iterators into the first
std::copy( boost::make_counting_iterator(verts.begin())
, boost::make_counting_iterator(verts.end ())
, std::back_inserter(vert_iters)
);

vert_iter_list_t::iterator vert = vert_iters.begin();
std::advance(vert, 2);

typedef std::vector<vert_iter_list_t::iterator> vert_group_t;

vert_group_t vert_group(4);
vert_group[0] = vert;

vert_group_t::value_type::value_type vert_2 = *v_group[0];
vert_2->x = 1.0f;

Share this post


Link to post
Share on other sites
Hi guys,

Thanks for the re-assurance. After two hours of mild frustration I realized I was committing the classic error or refrencing a pointer that goes out of scope:

void FunctionX()
{

Vertex* v=...;

// stored pointer causes error later on
v_group[0]=&v;

}

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