Another 'pointer to pointer' question

C

Christopher

I want to expand on another post I had asked earlier, but change
something and see if it is still OK.

Old post summary:

Q-
I need to have an array of pointers to something. I do not know how
many I will have until runtime. How do you allocate? It needs to be in
the form: type **, because the API I am using asks for it in that
way.

A-
Use std::vector

#include <vector>

void some_function(int**);

class A
{
A()
{
// append with push_back
for (int i = 1; i < 4; ++i) {
m_integers.push_back( new int(i) );
}

// pass to C API
int** pint = &m_integers[0];
some_function(pint);
}

// add copy, assignment and destructor
// remember to delete the ints

private:
std::vector<int*> m_integers;
};

That worked great. Now I am going to end up having alot of these
buffers, but only need to pass a few to the API. Which ones will be
dynamic. I want to see if I involve a map of pointers, if the code is
still going to be OK. I know a map is not contiguous like a vector,
but I don't know if it matters when I just store pointers in the map?

Lemme see if I can code this example:

#include <vector>

// In thier C API, the buffer is some other thing they do not describe
// I just get a pointer to it. I just made this a vector for the
example
typedef std::vector<int> Buffer;
void some_function(Buffer **);

class A
{
A()
{
// Create the master collection of buffers
Buffer * buffer = new Buffer();
for (int i = 0; i < 3; ++i)
{
buffer->push_back(i);
}
m_master.push_back("Numbers", buffer);

buffer = new Buffer();
for (int i = 0; i < 3; ++i)
{
buffer->push_back(i);
}
m_master.push_back("Indices", buffer);

buffer = new Buffer();
for (int i = 0; i < 3; ++i)
{
buffer->push_back(i);
}
m_master.push_back("Kilometers", buffer);

// Pass only the needed buffers to the C API
m_current.push_back( m_master["Numbers"] );
m_current.push_back( m_master["Indices"] );

Buffer ** pBuffers = &(m_current[0]);
some_function(pBuffers);
}

// add copy, assignment and destructor
// remember to delete allocated memory

private:

typedef std::map<std::string, Buffer *> MasterBufferCollection;
MasterBufferCollection m_master;

typedef std::vector<Buffer *> CurrentBuffers;
CurrentBuffers m_current;
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top