Convert char [] [] to char **

I have char[][]

  char c[2][2]={
    {'a','b'},
    {'c','d'}
  };

How to convert it to char**?

The goal is to use the transformed char**as input for the main function, which takes only char**as its input. Both C / C ++ solutions are acceptable.

+4
source share
4 answers

While you can easily switch from, char[]to char*, char[][]and char**this is not possible:

  • yours char[2][2]is a 2-dimensional array containing all the elements stored contiguously. To access a single element, the compiler calculates the offset, knowing the size of each line.
  • char** , char. , , poitner, .

:

char *pc[2]={c[0],c[1]}; 
cout << pc[1][1]<<endl;   // prints out the same as c[1][1]
// you can pass `pc` when a `char**` is needed

: . , char **av , av[i] c-. , , , ( ).

+5

char[2][2] char**, char(*)[2],

char (*p)[2] = c;

-2-w980. , 2 char** p, ( , "" , t ( )).

+2

:

char c[2][2] = {
    {'a','b'},
    {'c','d'}
};

char* x[] { c[0], c[1] };
func(x); // Assuming something like: void func(char** p);
+2

.. / , , char*[2]; new, .

:

char c[2][2] char. 4 char .

When you create an array of arrays ( char** c), you need to manually select an array of pointers to char, and then select (or assign) an array to chareach of these pointers.

So, to convert an array char c[2][2]to an array of arrays, you first need to create an array of pointers, and then assign that array the first element of each char array.

Something like that:

void func(char** c)
{
    for(int x = 0; x < 2; ++x)
        for(int y = 0; y < 2; ++y)
            std::cout << c[x][y] << ' ';
    std::cout << '\n';
}

int main(int, char* argv[])
{
    // one contiguous block of 4 chars
    char c[2][2]={
        {'a','b'},
        {'c','d'}
      };

    char** param = new char*[2]; // create your own pointer array
    param[0] = &c[0][0]; // assign the first element of each char array
    param[1] = &c[1][0];

    func(param); // call your func

    delete[] param; // cleanup
}

If you have one C++11, you can use the smart pointer to prevent a memory leak if an exception is thrown or someone has forgotten delete.

int main(int, char* argv[])
{
    // one contiguous block of 4 chars
    char c[2][2]={
        {'a','b'},
        {'c','d'}
      };

    // use a smart pointer
    std::unique_ptr<char*[]> param(new char*[2]);
    param[0] = &c[0][0];
    param[1] = &c[1][0];

    func(param.get()); // now if this throws, no memory leak

    // delete[] param; // NO NEED TO DELETE
}
+1
source

All Articles