Returning an Array from a function

Hi there,

Bit of a quick background - I'm a developer experienced in C# and am currently trying to learn C++ (using Win32 API).

As part of an exercise I'm doing, I'd like to have a function that populates a TCHAR array and returns it.

The problem is, the array is being filled in correctly but the returned value is completely different?

I'm not sure on what I may be doing wrong so I appreciate any help.

Basically I'd like to be able to do this

MessageBox(hWnd, GetButtonState(hWnd, TL) , _T("text"), NULL);

Where GetButtonState is defined as:

TCHAR* GetButtonState(HWND hWnd, GamePosition butonPosition){
// Create String Buffer for populating Button text
TCHAR wndwTxt[5];
// Retrieve Button text and store in Buffer
GetDlgItemText(hWnd, GetDlgCtrlID((HWND)buttonList[butonPosition]), wndwTxt, 5);

return wndwTxt;
}

Now, if I debug and go into the GetButtonState function, the text is being populated correctly. Even if I do a Watch on GetButtonState - I'll get the correct value.

However the Messagebox is showing random characters?

Having said that I'm not sure if this could be a Win32 API issue with character encoding?

Anyone able to help?

Thanks in advance,

Matt!
The array is a local variable and is therefore destroyed once you leave the functions scope, so you should try using dynamically allocated memory instead
closed account (zb0S216C)
Your compiler may not support array returns. However, you can have a parameter that takes a reference or pointer to an array. For example:

1
2
3
4
int GetMax( int( &Array )[ 2 ] )
{
    return( ( Array[ 0 ] > Array[ 1 ] ) ? Array[ 0 ] : Array[ 1 ] );
}

Wazzak
Excellent!

Thanks so much for your help. I looked into dynamic memory allocation and sorted it out.
Topic archived. No new replies allowed.