这个源代码有几个问题。
首先,您有一个带有局部变量的函数,堆栈上的一个变量,它返回该变量的地址,但是当函数返回时,变量消失并且地址不再有效。
下一个问题是您没有比较字符串。相反,您正在比较函数返回的地址,如果幸运的话,地址可能是相同的。由于您连续两次调用该函数,因此您很幸运,因此地址相同。
我建议您执行以下操作:(1)在调用该函数的函数中创建两个本地字符串,GetRegistry()
以及(2)修改该GetRegistry()
函数,使其使用这些缓冲区而不是它自己的缓冲区。所以代码看起来像:
char registryEntryOne[1024];
char registryEntryTwo[1024];
DWORD dwRegistryEntryOneLen;
DWORD dwRegistryEntryTwoLen;
registryEntryOne[0] = 0; // init the registry entry to zero length string
registryEntryTwo[0] = 0;
dwRegistryEntryOneLen = sizeof(registryEntryOne);
GetRegistry ("First", registryEntryOne, &dwRegistryEntryOneLen);
dwRegistryEntryTwoLen = sizeof(registryEntryTwo);
GetRegistry ("Second", registryEntryTwo, &dwRegistryEntryTwoLen);
// two strings are equal if:
// the lengths are the same
// at least one of the lengths is non-zero
// the bytes are the same in the same order
if (dwRegistryEntryOneLen && dwRegistryEntryOneLen == dwRegistryEntryTwoLen && memcmp (registryEntryOne, registryEntryTwo, dwRegistryEntryOneLen) == 0) {
// strings are equal
} else {
// strings are not equal
}
GetRegistry() 函数看起来像:
char* GetRegistry(char* StringName, char *valueBuffer, DWORD *value_length)
{
DWORD dwType = REG_SZ;
HKEY hKey = 0;
const char* subkey = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\MCI\\Player";
RegOpenKey(HKEY_LOCAL_MACHINE,subkey,&hKey);
RegQueryValueEx(hKey, StringName, NULL, &dwType, (LPBYTE)valueBuffer, value_length);
return valueBuffer;
}