This all stems from C where pointers are the only choice. In short: you can't. Which is why you shouldn't use this.
But you can do some guessing:
Any function reading a C string should use const char *
. Passing a pointer to a single const char makes no sense as you could just pass the char directly. So it's safe to assume it's a 0 terminated string.
Any function writing to a char array will have to also know the size. So if you see char *ptr, size_t len
you can be sure it's a pointer to a buffer of memory.
Now the next question is: Will the function free the pointer? Will it store the pointer for later use? Those you can't even guess.
Which brings us to the not using it part and entering the world of modern C++:
The C++ Core Guidelines make some suggestion about how to write your interface to make it clear in code what the semantics are.
First forget all about C string and arrays. They are bad. Don't use them.
For strings use std::string
. For string literals you can use
using namespace std::literals
auto s = "this is a std::string literal"s;
Simple C string literals ("Hello World!"
) will be converted to std::string automatically when needed. But they can just as easily be passed to a function taking a char *
. The s
suffix makes it explicit that you want a std::string
so no accidents can happen.
For arrays use std::vector
or std::array
instead. And even if you have to use C arrays for some reason use std::span
to pass them around. From that follows that any char *
should be a pointer to a single char.
If the function takes ownership of the pointer it should be std::unique_ptr<char>
instead and if the function stores the pointer for later use but doesn't handle freeing it then it should be std::shared_ptr<char>
. So any char *
means a pointer to single char that is only used for the duration of the function and you have to free it later.
Note: this applies to any type, not just char.
Note2: If you can passing a char&
would be better as that signals the "pointer" can't be nullptr. A char*
argument should always be checked for nullptr.