Search code examples
c++functiondouble-pointer

Double pointer as parameter


I have the follow prototype:

int Split(const char* str, const char* delim,unsigned int& numtokens,char **tokensRes)

The last parameter is used to return the response of this function. In the function we have the follow:

.
.
char **tokens =(char**) calloc(tokens_alloc, sizeof(char*));
.
.
.
//at the end of the code
tokensRes = tokens;
.

When returns the value of tokens variable direct when the return of the function is char** I receive the correct answer, but using the method above the return of the function came empty. How can I make this function work correctly?

EDIT 1: My intent is receive an array of char arrays, eg:

array[0] = "ABC"
array[1] = "ABC"
array[2] = "ABC"
array[3] = "ABC"

Solution

  • Change the prototype from:

    int Split(const char* str, const char* delim,unsigned int& numtokens,char **tokensRes)
    

    To:

    int Split(const char* str, const char* delim,unsigned int& numtokens,char ** &tokensRes)
    

    And the code tokensRes = tokens; will work. To understand why learn more about C++ and references.

    Other answers about using strings are valid if you're planning to move from a C style of coding to a C++ one. The ease of coding would improve a lot and no worries about memory management and pointers (well not often), which are done automatically by classes. No worries about a performance decrease either as long as you follow good practices such as passing objects by reference and not value.