logeeks
logeeks

Reputation: 4979

manipulating values using TCHAR*

I am writing the following code

void MaskSensitiveData(TCHAR* szData,bool bEncryptAll)
{
    szData = L"Test";
}
    
void CMFCTestDlg::OnBnClickedButton1()
{
    TCHAR szTest[100] = L"This is a Password:myPass";
    MaskSensitiveData(szTest,false);
    AfxMessageBox(szTest);
}

I am expecting that the MaskSensitiveData method alters the szTest and the value is passed back to the caller. I see the value is not getting changed. Can you please tell me what I can do to edit the value inside the calling function?

Upvotes: 0

Views: 101

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596352

In MaskSensitiveData(), the szData parameter is being passed by value, so a copy of the pointer is being made, and any new value assigned to szData itself inside of MaskSensitiveData() will be assigned to that copy and not be reflected back to the caller's original variable.

Also, this code shouldn't even compile, as a string literal is an array of const characters (ie, L"Test" is a const wchar_t[5]), which decays into a pointer-to-const, but szData is a pointer-to-non-const instead, which is not allowed to point at const data.

You need to instead copy the contents of the string literal into the memory that szData is pointing at, eg:

void MaskSensitiveData(TCHAR* szData, int iDataLen, bool bEncryptAll)
{
   _tcscpy_s(szData, iDataLen, TEXT("Test"));
}
    
void CMFCTestDlg::OnBnClickedButton1()
{
    TCHAR szTest[100] = TEXT("This is a Password:myPass");
    MaskSensitiveData(szTest, 100, false);
    AfxMessageBox(szTest);
}

Upvotes: 1

Related Questions