clambake
clambake

Reputation: 822

Passing Pointer to Function Anomaly

Why would the output of the below program be 0x0?

BYTE n_buffer[4] = { 1, 2, 3, 4};

int GetElement(BYTE *pElement, DWORD dwIndex)
{
    pElement = &n_buffer[dwIndex];
    return SUCCESS;
}

int main()
{
    BYTE *res2 = NULL;
    GetElement(res2, 3);
    printf("0x%X\n", res2);
}

Upvotes: 0

Views: 47

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

Function parameters are local variables of the function. After exiting the function they are destroyed.

You may imagine function GetElement

int GetElement(BYTE *pElement, DWORD dwIndex)
{
    pElement = &n_buffer[dwIndex];
    return SUCCESS;
}

and its call

BYTE *res2 = NULL;
GetElement(res2, 3);

the following way

int GetElement()
{
    BYTE *pElement = res2, 
    DWORD dwIndex = 3;

    pElement = &n_buffer[dwIndex];
    return SUCCESS;
}

Thus because pElement has a copy of the value of res2 res2 itself will not be changed.

You should define the function and call it the following way

int GetElement(BYTE **pElement, DWORD dwIndex)
{
    *pElement = &n_buffer[dwIndex];
    return SUCCESS;
}

// ...

BYTE *res2 = NULL;
GetElement( &res2, 3 );

The other approach is to define the function like

BYTE * GetElement( DWORD dwIndex)
{
    return (dwIndex < 4 ? &n_buffer[dwIndex] : NULL );
}

// ...

BYTE *res2 = NULL;
res2 = GetElement( 3 );

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your GetElement() function, res2 has been passed using pass-by-value. pElement is local to GetElement() function.

Any changes to *pElement will be reflected back in main(), changes to pElement itself won't.

So, after returning from GetElement() function, res2 in main() will still be NULL.

Note: if you want to change res2 from GetElement() function, you need to pass a pointer to res2 as argument.

Upvotes: 3

EffegiWeb
EffegiWeb

Reputation: 184

try

int GetElement(BYTE **pElement, DWORD dwIndex)
{
    *pElement = &n_buffer[dwIndex];
    return SUCCESS;
}

and the main

int main()
{
    BYTE *res2 = NULL;
    GetElement(&res2, 3);
    printf("0x%X\n", res2);
}

Upvotes: 1

antonpuz
antonpuz

Reputation: 3316

You dont return any pointers, my guess is that you want to pass the address of the pointer and assign its value

int GetElement(BYTE **pElement, DWORD dwIndex)
{
 *pElement = &n_buffer[dwIndex];
 return SUCCESS;
}

Try to draw the the pointers and where they point and read a little bit more about pointers.

Upvotes: 3

Related Questions