0

Possible Duplicate:
Char array gives error when initializing

I want to insert an environment variable in the windows registry, so i tied the following C++ code :

string appDataPath = getenv("appdata");

    HKEY hkey;
    char value[] = appDataPath.c_str();

    RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\Currentversion\\Run", 0, KEY_SET_VALUE, &hkey);
    RegSetValueEx (hkey, "MyProgram", 0, REG_SZ, (LPBYTE) value, strlen(value) + 1);
    RegCloseKey(hkey);

The codeblock debug output tell me : error: initializer fails to determine size of 'value' I think it's because the compilator need to know the size of my variable before compiling, however i don't know how to fix that...

Thanks !

Community
  • 1
  • 1
  • Arrays are not pointers? (recommended reading: http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c and http://stackoverflow.com/q/388242/46642) – R. Martinho Fernandes Jan 21 '13 at 14:22

2 Answers2

1

c_str() returns a const char*, not a char[]. Change

char value[] = appDataPath.c_str();

to

const char* value = appDataPath.c_str();

The compiler is giving the error because an array variable requires a length - which is not being provided.

shf301
  • 31,086
  • 2
  • 52
  • 86
0

Use

const char * value = appDataPath.c_str();

(Read the < string > reference to find the return type of c_str(), it will tell you that it is indeed const char *.)


Regarding your question of how to concatenate two strings:

Do that with C++ strings rather than with char *s and convert them later:

string newstring = appDataPath;
newstring.append("some text");
const char * value = newstring.c_str();
us2012
  • 16,083
  • 3
  • 46
  • 62