I have a simple question C++ (or C). Why does the following program, passing c string to function, not produce the desired output?
#include <cstdio>
#include <cstring>
void fillMeUpSomeMore( char** strOut )
{
strcpy( *strOut, "Hello Tommy" );
}
int main()
{
char str[30];
//char* strNew = new char[30];
fillMeUpSomeMore( (char**) &str ); // I believe this is undefined behavior but why?
//fillMeUpSomeMore( (char**) &strNew ); // this does work
std::printf( "%s\n", str );
//std::printf( "%s\n", strNew ); // prints "Hello Tommy"
//delete[] strNew;
}
All I'm doing is passing the address of the char array str to a function taking pointer to pointer to char (which after the explicit conversion should be just fine). But then the program prints nothing. However this will work with the strNew variable that has been dynamically allocated.
I know that I shouldn't be doing this and be using std::string
instead. I'm only doing this for study purposes. Thanks.
I'm compiling with g++ & C++17 (-std=c++17).