I have :
void func()
{
char *s;
strcpy(s,"bla bla");
}
Is "bla bla" stored somewhere? is it considered "const char *" even if I didn't defined it??
I have :
void func()
{
char *s;
strcpy(s,"bla bla");
}
Is "bla bla" stored somewhere? is it considered "const char *" even if I didn't defined it??
String literals are nameless array objects, which are stored in static memory, i.e. the same memory that stores global variables. String literals live forever: they exist when the program begins and they persist till the program ends (just like global variables, again).
Note however, that in your code sample it is "blah blah"
that's string literal. But your s
is just a local variable initialized (by copying data) from string literal. Your s
has the same lifetime as any other local variable - it exists as long as the control passes through func
.
Note also that string literal in C is not considered const chart *
, as you seem to incorrectly believe. The type of "blah blah"
in C language is actually char [10]
. The array type can decay to pointer type, but even in that case it will be char *
and not const char *
.
"blah blah"
is stored on the stack, just like any other automatic variable or array declared inside a function.
The construction
char s[] = "blah blah";
is equivalent to
char s[] = {'b', 'l', 'a', 'h', ' ', 'b', 'l', 'a', 'h', '\0'};
and it initializes the array.
You can treat arrays of chars as char * const
, because they behave in nearly the same way as arrays, but technically speaking, an array is an array, and a pointer is a pointer.
This is not, however the same as const char *
. char * const
means the pointer cannot be modified, const char *
means the memory cannot be modified through that pointer.