I'm trying to understand why the following string passing works for my error string. I have made this example from a much bigger source I have.
My question is; why don't I have to specifically allocate memory for the char array which contains my error message? I would have thought that I need to malloc some memory for the string and use the err pointer to indicate the start of this memory.
Is this to do with that fact that its a const char *
or is is because I'm printing to stderr?
I'm possibly wording the question wrong which is why searches haven't helped me to understand this.
const char * my_function(int a)
{
if (a != 1)
return "a doesn't equal 1!"
else
return NULL;
}
int main(int a)
{
const char *err;
err = my_function(a);
if (err)
fprintf(stderr, "Message = %s\n",err);
return 1;
return 0;
}
In C and C++, const translates more or less to "read only". So, when something returns a char const * , that doesn't necessarily mean the data it's pointing at is actually const --it just means that the pointer you're receiving only supports reading, not writing, the data it points at.
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
7.8 Member Function Return Typesconst char* function (...) returns a pointer to data that cannot change. The caller can see the data but the compiler will reject any code that may change the data. The caller must assign the result to a const char* variable or pass as a const char* argument.
1 Answer. Show activity on this post. string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
All string literals are allocated at compile time. They already reside in a read-only section of the program memory when your program is started; they aren't allocated in runtime. You can regard them as constant character arrays. And like any const
variable, they remain valid throughout the whole execution of the program.
String literals are allocated as const char arrays with static storage duration, so they live for the entire lifetime of the program. The scope they happen to be in is irrelevant -- they always have static storage duration.
That means you can take their address (which happen implicitly if you return a string literal or store it in a const char * variable anywhere) without having to worry about the lifetime of the resulting pointer. The storage for the string literal will never be used for something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With