0

I've wrote a method that convert form CString to const char *:

const char* CAESDlg::ConvertToChar(CString str) {
    CStringA charstr(str);
    const char *cstr = (const char *)charstr;
    return cstr;
}

but when trying to put it in a const char * it doesn't return the correct value!

const char *test = ConvertToChar(filePath);
m0nhawk
  • 22,980
  • 9
  • 45
  • 73
Ahmed Ali
  • 2,574
  • 2
  • 23
  • 38

2 Answers2

1

Without knowing CString and CStringA I can only guess, but it seems as if you are returning a pointer to a local variable, which is UB, as soon as you access value the pointer points to.

If you want to use a CString object as a const char* parameter you probably want to use LPCTSTR instead of your self-written ConvertToChar function.

MikeMB
  • 20,029
  • 9
  • 57
  • 102
  • @AhmedAli: There are multiple possibilities, depending on how you want to use the function, but personally I'd suggest not to use `const char*` at all, but `std::string`. Btw: you should probably have a look at [this question](http://stackoverflow.com/questions/859304/convert-cstring-to-const-char) – MikeMB Apr 25 '15 at 09:43
  • @AhmedAli: See my edit in response to the information in your comments. – MikeMB Apr 25 '15 at 09:57
  • i got this error while trying to use LPCTSTR a value of type LPCTSTR can't be used to initialize an entity of type const char * – Ahmed Ali Apr 25 '15 at 10:11
1

The value of charstr gets destroyed at the end of the function before the caller assigns it to variable.

You don't need a function, the caller can use CStringA directly and note that test is valid before sFilePathA goes out of scope.

CStringA sFilePathA(filePath);
const char *test = sFilePathA;
Roman R.
  • 68,205
  • 6
  • 94
  • 158