Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 346
RobertoNovelo Avatar asked Mar 09 '13 21:03

RobertoNovelo


1 Answers

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);
    //       ^
}
like image 120
Andy Prowl Avatar answered Oct 11 '22 17:10

Andy Prowl