How do you convert char* to a string. I've tried so many ways but I keep getting errors. I need convert them so i can combine the strings for a function.
1) You have to give a buffer to getcwd. You can't give it 'NULL' or it will have nowhere to put the string data.
2) wd is a pointer. sizeof(a_pointer) gives you the size of a pointer (ie: probably 4 or 8 bytes, depending on your system), not the size of the data pointed to by the pointer.
3) strncat/strncat_s/strcat appends data to the end of an existing string. In this case, you are trying to append data to the end of fPath, but you never put anything in fPath (it's uninitialized) so there is no "end". You are potentially corrupting memory.
Do this:
1 2 3 4 5 6 7 8 9
char wd[256]; // use an actual buffer, not a pointer
getcwd( wd, 256 ); // give that buffer to getcwd and tell it how big the buffer is.
// if you want to put that data in a string...
string cwd = wd; // like "long double main" suggested
// or if you want to copy it to a different char array (why?)
char wd2[256];
strcpy( wd2, wd ); // strcpy, not strcat
Thanks, I didn't know the string constructor took char*. BTW _getcwd can take NULL. It allocates memory for the buffer automatically so that it is the smallest size possible and allows it to be bigger than maxpath.
It explains it in this example... http://msdn.microsoft.com/en-us/library/sf98bd4y(v=vs.100).aspx
man getcwd
getcwd() allocates the buffer dynamically using malloc(3) if buf is NULL.
Your buf is not NULL therefore the memory is not allocated. Your wdc is not from the heap so you can't free it.
char buffer3[50]; // note buffer3 must be large enough to hold both strings + null terminator
strcpy( buffer3, buffer1 ); // copy buffer1 to buffer3
strcat( buffer3, buffer2 ); // append buffer2 to buffer3