Solved

CString to char []

Posted on 1998-03-14
11
584 Views
Last Modified: 2013-11-19
I need to copy from CString to char[].  I read about the GetBuffer() and ReleaseBuffer() and wondering if it is needed here:

char Des[256] ;
CString Src = "Source" ;

if (Src.GetLength <= 255)
  strcpy (Des, Src) ; // no error

Or should it be

int n = Src.GetLength()
if (n <= 255)
{
 strcpy (Des, Src.GetBuffer(n)) ; // no error
 Src.ReleaseBuffer( );
}
0
Comment
Question by:leowlf
  • 3
  • 3
  • 2
  • +3
11 Comments
 
LVL 8

Expert Comment

by:MikeP090797
ID: 1316976
The MFC help referense says:
If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.

so, as long as you don't make any changes on the pointer you got, and in this case you don't there is no need in ReleaseBuffer
0
 

Author Comment

by:leowlf
ID: 1316977
What about this? No error. But is it technically correct?

    char Des[256] ;
    CString Src = "Source" ;

    if (Src.GetLength <= 255)
      strcpy (Des, Src) ; // no error
0
 
LVL 8

Expert Comment

by:MikeP090797
ID: 1316978
What do you mean by 'technicly correct'?
Everything is correct as long as it works, in programming there is no correct/not correct - IF IT WORKS, IT IS CORRECT
0
 
LVL 3

Expert Comment

by:stefanr
ID: 1316979
Probably a typo, but shouldn't the statement be
if (Src.GetLength() <= 255)`?
0
 
LVL 8

Expert Comment

by:MikeP090797
ID: 1316980
It should
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 11

Expert Comment

by:mikeblas
ID: 1316981
MikeP's answer is why the software industry is in such a shambles.  There _is_ a right and wrong; just because something "works" doesn't mean it is correct!

This is a science, not an art. Programmers need to work on getting things right, not hacking around until "it works".

.B ekiM
0
 

Author Comment

by:leowlf
ID: 1316982
I better reopen the question.
Is it technically correct if i do this without using GetBuffer(n) to do the copying?

char Des[256] ;
CString Src = "Source" ;

if (Src.GetLength() <= 255)
  strcpy (Des, Src) ;

I have not encounntered any error at runtime yet, but it could bomb out anytime if it done technically wrong.
0
 
LVL 1

Expert Comment

by:Nexial
ID: 1316983
Sorry, MikeP, but
"If it works,it is correct", is only valid if it is a ONE TIME
USE, throwaway program, that will neither be retained nor reused
nor supported.  i.e. a thrown together "HACK" to verify a fact
or check a response.   IT IS NOT SUITABLE FOR PRODUCTION CODE.
0
 
LVL 6

Accepted Solution

by:
jpk041897 earned 50 total points
ID: 1316984
Going back to your original question, GetBuffer() and ReleaseBuffer are not needed  to copy a CString to char[].

There are two ways you can access the char[] contained in a CString:

a) Casting via LPCSTR defined as:

 operator LPCTSTR ( ) const;

which returns a const char*.

b) GetBuffer defined as:

LPTSTR GetBuffer( int nMinBufLength );
throw( CMemoryException );

which returns a char *.

If all you intend is to copy the contents of the CString to an array then you would use:

    char Des[256] ;
    CString Src = "Source" ;

    if (Src.GetLength() <= 255)
      strcpy (Des, LPCSTR(Src)) ; // no error

since this code insures that the char[] contained in Src is not accidentaly modified.

You would need GetBuffer if you wanted to do the opposite, that is:



    char Des[256] ;
    CString Src = "Source" ;
    try{
       if (Src.GetLength() <= 255)
         strcpy (Src.GetBuffer(), Des) ; // no error
       }
    catch CMemoryException{
      // error procesing here
    }
  Src.ReleaseBuffer();
0
 
LVL 11

Expert Comment

by:mikeblas
ID: 1316985
JPK's "do the opposite" example is a little confusing and won't even compile.

In JPK's code, Des[] isn't initialized to anything. Caling strcpy() with it as the source string is likely to cause a crash. There's no reason to test the length of the existing string, as GetBuffer() takes a parameter for the minimum length the CString object will contain. Since JPK doesn't supply that parameter, the code won't compile.

It's not the missing parameter that's a problem: it's the idea that you have to call GetLength() that's confusing. You don't need to call GetLength()!  The parameter to GetBuffer() assures that you have at least that many chracters at the pointer returned from your GetBuffer() call.

Finally, GetBuffer() doesn't return a char*. It returns a LPTSTR. Sometimes, a char* is the same thing as a LPTSTR, but if _UNICODE is defined it certainly is not the same thing.

So, you should code the "going the other way" example like this:

TCHAR szSource[] = _T("Hockey is best!");
CString strDest;
try
{
   LPTSTR pstr = strDest.GetBuffer(lstrlen(szSource));
   lstrcpy(pstr, szSource);
}
catch (CMemoryException* pEx)
{
   // error processing here
   pEx->Delete();
}
strDest.ReleaseBuffer();

Of course, this example is completely academic because using GetBuffer() to assign a string to a CStr is completely unnecessary. You should just use the assignment operator:

TCHAR szSource[] = _T("Hockey is best!");
CString strDest;
strDest = szSource;

and get it done in one small call.

The bottom line is: using CString isn't that hard, and is very well-documented.  It's impossible for me to understand why this thread has gone on for so long and has so much dubious code and bad advice.

.B ekiM

0
 
LVL 11

Expert Comment

by:mikeblas
ID: 1316986
Oh, and JPK's exeception handler is wrong, too.  It won't compile, either... and never calls Delete() on the thrown object.

.B ekiM
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Decoding 32 bit binary streams 6 37
Show shut-down message as Windows 8 shuts down. 9 85
Replacement selected text 2 58
How to know only "File created" with EventLog 3 32
In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
Introduction: Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events. Continuing from the fourth article about sudoku. …
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now