i have some problems to reverse LPSTR. Here is my function:
LPSTR Reverse(LPSTR a_lpText)
{
int nTextLength = strlen((char*)a_lpText);
LPSTR lpReversed = (LPSTR) GlobalAlloc(GPTR, nTextLength + 1);
for (int i = 0; i < nTextLength; ++i)
*(lpReversed + i) = (CHAR) *(a_lpText + nTextLength - i);
return lpReversed;
}
Function, return not initialized LPSTR or some strange characters. Problem is probably in conversion? Thanks for answers!
Edit 1: strcat() don't work. I just want copy char by char.
Edit 2:
*(lpReversed + i) = (CHAR) *(a_lpText + nTextLength - i - 1);
Freeze the whole program.
This looks more like C code than C++, so I'll stick to that style. I can't understand why you would be using
GlobalAlloc
. You only need that for DDE which I cannot possibly imagine you are using here. Usemalloc
ornew[]
if this really is C++.If you really are using a DDE API that requires
GlobalAlloc
, then keep theGlobalAlloc
part separate from the string reversing code. Mixing the two concerns makes for unmaintainable code.If this really is C++ then
std::string
is what you should be using wherever possible.I also think there's great confusion with all the casting and all the non-standard Windows type macros. It makes the code pretty much unreadable.
There is also an indexing error as pointed out by Maximus. For what it is worth, I'd write the function something like this:
The only cast you need is the return value of
malloc
. If you were to usenew[]
then you would not even need to do that. In which case the code would be like this:One should always strive to write code without casts.
Don't do pointer arithmetic yourself when the index operator
[]
can be used. It's much easier to read this way.