Search code examples
c++cpointersmicrocontroller

Increment the value of a pointer when sent as a parameter


I am stuck in the following pointer problem:

Say you have a function:

void Function (unsigned char *ubPointer)
{
    ubPointer++;
}

int main (void)
{
    unsigned char *PointerX;

    Function( PointerX );
}

What I want is that the ++ is reflected in PointerX, without declaring it as a global variable.

Thank you very much.


Solution

  • In C++, pass your pointer by reference (and don't forget to specify a return type for your function):

    void Function (unsigned char*& ubPointer)
    //                           ^
    {
        ubPointer++;
    }
    

    This won't require any further change in the calling code. When returning from the function, the side-effects on ubPointer will be visible to the caller.

    In C, you can achieve the equivalent result by passing a pointer to your pointer:

    void Function (unsigned char** ubPointer)
    //                           ^
    {
        (*ubPointer)++;
    //  ^^^^^^^^^^^^
    }
    

    This will require you to change the way you are calling your function:

    int main()
    {
        unsigned char* p;
        Function(&p);
        //       ^
    }