You can just make your input parameter of your function a const char*
and it will work. A function that has its input parameter as const char*
means that the function will not make changes to what the pointer points to! So this means it will work with both string literlas (which are const char*
themselves) and with regular char*
parameters.
void printString(const char* str)
{
printf("%s", str);
}
This function can be called like this:
int main()
{
const char* pointerToLiteral = "string";
char* str = new char[16];
std::strcpy(str, pointerToLiteral );
printString("true literal");
printString(pointerToLiteral );
printString(str);
delete [] str;
}
When you pass a pointer to printString
function it makes a copy of that pointer on its stack. And that copy is now of type const char*
. Which means that the code of printString
cannot change what the pointer points to. There is no reason this would not work if you pass a pointer of type char*
to it.
Note that the other way around does not work. If we had printString(char* str)
, you cannot pass it a const char*
parameter, because now the function is saying that it can make changes to what the pointer points too, but the const char*
parameter does not allow that!