0

I googled it for 2 hours now, and i can't find an answer for my problem: i need to get a registry REG_SZ value and pass it to a char*.

char host_val[1024]; DWORD hostVal_size = 1024; char* hostName; DWORD dwType = REG_SZ; RegOpenKeyEx(//no problem here); if( RegQueryValueEx( hKey, TEXT("HostName"), 0, &dwType, (LPBYTE)&host_val, &hostVal_size ) == ERROR_SUCCESS ) { //hostName = host_val; } 

How should i do this conversion hostName = host_val?

2
  • What's the problem exactly? to convert char array of fixed lenth to char *? Commented Sep 7, 2012 at 6:04
  • @SingerOfTheFall, yes, the conversion is my problem. Commented Sep 7, 2012 at 6:32

3 Answers 3

4

The resulting host_val is a possibly non-null-terminated string (see "Remarks"), so you should copy it to a newly allocated string with memcpy, and ensure it's null-terminated:

hostName = new char[hostVal_size + 1]; // host_val may or may not be null-terminated memcpy(hostName, host_val, hostVal_size); hostName[hostVal_size] = '\0'; 

You will need to delete[] the hostName later.

Sign up to request clarification or add additional context in comments.

1 Comment

the value in my registry is an IP address, say, 192.168.1.219. Using RegQueryValueEx that value is passed to host_val, but after using your code all that is copied to hostName is 1.
3

use the ANSI version of the function

RegQueryValueExA 

that way you don't need to convert.

Comments

2

If you're compiling with Unicode you're copying a Unicode string (that is possibly NOT terminated) into a narrow char buffer. the first character in the unicode string will be 0x3100 (accounting for the endianness on your machine, which is likely little-endian, and the fact that you said the IP address is 192....)

That value stuffed into the char[] array will report back as a single-char-null-terminated string. You have two options.

  1. Use RegQueryValueExA, everything else stays the same, or
  2. Change your char[] array to a wchar_t[] array, do what you're currently doing, then convert to narrow using WideCharToMultiByte(docs are in the SDK).

For obvious reasons, I'd take the former of those two options.

2 Comments

if i use RegQueryValueExA i get an error C2664: 'RegQueryValueExA' : cannot convert parameter 2 from 'const wchar_t [9]' to 'LPCSTR'
Take out the TEXT() macro wrapper, for your string literals on that call.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.