Problem

R

renbin

Now I have a problem. I have some code like this:

void SetFieldName(LPCTSTR lpszNewValue)
{
char szFieldName[11];
strcpy(szFieldName,lpszNewValue);
}

When I debug it,the System tells me
"Error 1 error C2664: 'strcpy' : cannot convert parameter 2 from 'LPCTSTR'
to 'const char *' e:\MapControlTest\Map\MapTableDesc.cpp line 74"

Please tell me where my code wrong,thank you.
 
B

Bruno van Dooren [MVP VC++]

void SetFieldName(LPCTSTR lpszNewValue)
{
char szFieldName[11];
strcpy(szFieldName,lpszNewValue);
}

When I debug it,the System tells me
"Error 1 error C2664: 'strcpy' : cannot convert parameter 2 from 'LPCTSTR'
to 'const char *' e:\MapControlTest\Map\MapTableDesc.cpp line 74"

strcpy takes char arrays as parameters, your lpszNewValue is probably a
unicode string.
if you want to use TSTR, you should use
_tcscpy

to insure that you use the correct function.

additionally:
-Your code is dangerous because you don't check that szFieldName is large
enough to hold lpszNewValue.
-drop the lpsz prefixes for variable names. These days there is absolutely
no reason anymore to use it. The compiler will tell you if you mix different
pointer types.
--

Kind regards,
Bruno van Dooren
(e-mail address removed)
Remove only "_nos_pam"
 
D

David Lowndes

When I debug it,the System tells me
"Error 1 error C2664: 'strcpy' : cannot convert parameter 2 from 'LPCTSTR'
to 'const char *' e:\MapControlTest\Map\MapTableDesc.cpp line 74"

You must be compiling a Unicode build, so your code should presumably
be:

void SetFieldName(LPCTSTR lpszNewValue)
{
TCHAR szFieldName[11];
_tcscpy(szFieldName,lpszNewValue);
}

.... unless you specifically need szFieldName as a MBCS - in which case
you somewhere need to convert from Unicode to MBCS - have a look at
the T2A macro documentation.

Dave
 
R

renbin

Hello Dave

I'm sorry that I don't want to change szFieldName type form char array to
TCHAR array.Do you have another method ?

I only want to copy lpszNewValue to char array,thank you!
 
D

David Lowndes

I'm sorry that I don't want to change szFieldName type form char array to
TCHAR array.Do you have another method ?

I only want to copy lpszNewValue to char array,thank you!

Is lpszNewValue actually a pointer to a Unicode string, or is it an
incorrectly defined MBCS string?

If it's the former, do as I mentioned originally:

"... unless you specifically need szFieldName as a MBCS - in which
case you somewhere need to convert from Unicode to MBCS - have a look
at the T2A macro documentation.
"

If it's the latter - define it correctly as LPCSTR.

Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top