#include <iostream>
const char* fun()
{
const char* x = "abc";
std::cout << "x = " << x << "\n";
return x;
}
int main(int arc, char** argv)
{
const char* y = fun();
std::cout << "y = " << y << "\n";
return 0;
}
Running this on my machine gives:
x = abc
y = abc
In fun()
, x
(a local variable) is assigned the address of a string literal created locally, yet when the function returns, the data pointed to by y
is the same as that pointed to by x
even though x
is out of scope.
Can someone explain in detail what is happening here?
In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed.
The const char *Str tells the compiler that the DATA the pointer points too is const . This means, Str can be changed within Func, but *Str cannot. As a copy of the pointer is passed to Func, any changes made to Str are not seen by main....
const char* is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so. For the same reason, conversion from const char * to char* is deprecated.
This is well-formed, the returned pointer is valid and not dangled; because the string literal (i.e. "abc"
) has static storage duration and exists in the whole life of the program.
String literals have static storage duration, and thus exist in memory for the life of the program.
As you said when the function returns the local variable x
gets destroyed, but the string literal pointed to by it doesn't.
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