Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert vector of vector to pointer of pointer

Assume I have a C library API function which takes pointer of pointers as parameter. However since I am programming in C++ I would like to take advantage of std vector to deal with the dynamic memory. How can I efficiently convert vector of vector into pointer of pointer? Right now I am using this.

#include <vector>

/* C like api */
void foo(short **psPtr, const int x, const int y);    

int main()
{
    const int x = 2, y = 3;
    std::vector<std::vector<short>> vvsVec(x, std::vector<short>(y, 0));
    short **psPtr = new short*[x];

    /* point psPtr to the vector */
    int c = 0;
    for (auto &vsVec : vvsVec)
        psPtr[c++] = &vsVec[0];

    /* api call */
    foo(psPtr, x, y);        

    delete[] psPtr;
    return 0;
}

Is this the best way to achieve the goal? Can I get rid of the "new delete" thing by using iterator or some std method in this case? Thanks in advance.

Edit: According to answers I am now using this version to interface with C code. I am posting it here.

#include <vector>

/* C like api */
void foo(short **psPtr, const int x, const int y);    

int main()
{
    const int x = 2, y = 3;
    std::vector<std::vector<short>> vvsVec(x, std::vector<short>(y, 0));
    std::vector<short*> vpsPtr(x, nullptr);

    /* point vpsPtr to the vector */
    int c = 0;
    for (auto &vsVec : vvsVec)
        vpsPtr[c++] = vsVec.data();

    /* api call */
    foo(vpsPtr.data(), x, y);        

    return 0;
}

Looks more C++ like to me. Thanks for all!

like image 234
yc2986 Avatar asked Feb 22 '17 19:02

yc2986


1 Answers

Is this the best way to achieve the goal?

If you are sure that the vector of vectors will outlive psPtr, then yes. Otherwise, you run the risk that psPtr will contain invalid pointers.

Can I get rid of the "new delete" thing by using iterator or some std method in this case?

Yes. I suggest using:

std::vector<short*> psPtr(vvsVec.size());

and then use &psPtr[0] in the call to the C API function. That removes the burden of memory management from your code.

foo(&psPtr[0]);        
like image 182
R Sahu Avatar answered Nov 02 '22 14:11

R Sahu