0

Trying to convert string to const char* gives "expression must have class type" at the bottom line. Tried some variations on converting with no luck. any ideas?

string GetMachineID()
    {
        // LPCTSTR szHD = "C:\\";  // ERROR
        string ss;
        ss = "Err_StringIsNull";
        UCHAR szFileSys[255],
            szVolNameBuff[255];
        DWORD dwSerial;
        DWORD dwMFL;
        DWORD dwSysFlags;
        int error = 0;

        bool success = GetVolumeInformation(LPCTSTR("C:\\"), (LPTSTR)szVolNameBuff,
            255, &dwSerial,
            &dwMFL, &dwSysFlags,
            (LPTSTR)szFileSys,
            255);
        if (!success)
        {
            ss = "Err_Not_Elevated";
        }
        stringstream errorStream;
        errorStream << dwSerial;
        return string(errorStream.str().c_str());
    }

    const char *cstr = GetMachineID.c_str();
b4hand
  • 9,550
  • 4
  • 44
  • 49
michealbell
  • 65
  • 2
  • 9

2 Answers2

6
const char *cstr = GetMachineID.c_str();

must be

const char *cstr = GetMachineID().c_str();

But anyway, think about what happens with your pointer. It will be dangling, since the std::string object returned by GetMachineId() is destroyed at the end of the statement.

You should either allocate memory for the pointer and use a strcpy, or, preferably, just get rid of char* in your code and use std::string everywhere.

Related: How to convert a std::string to const char* or char*?

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
1

You are making some big mistakes in this code, the most important of which is that you are completely mismanaging your text buffers, and using invalid type-casts. For that matter, you don't use the values that get stored in the buffers, so you don't need to allocate them at all, you can pass NULL for those parameters (and the others you don't use) so GetVolumeInformation() ignores them.

As for the actual compiler error, @vsoftco already answered that one. You are missing required parameters to actually call GetMachineID(), and you are mishandling the return value.

Use something more like this instead:

string GetMachineID()
{
    DWORD dwSerial;
    ostringstream oss;

    if (!GetVolumeInformation(TEXT("C:\\"), NULL, 0, &dwSerial, NULL, NULL, NULL, 0);
        oss << "Err_Not_Retrieved_" << GetLastError();
    else
        oss << dwSerial;

    return oss.str();
}

std::string machid = GetMachineID();
const char *cstr = machid.c_str();
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770