void f()
{
char *c = \"Hello World!\"
}
Where is the string stored? What\'s the property of it? I just know it is a constant, what else? Can I
It is generally stored in the read only section of memory and has static storage allocation.
Performing operations like c[0] = 'k'
etc invokes Undefined Behavior.
Can I return it from inside of the function body?
Yes!
It's implementation defined. Most of the time that would be stored in a string table with all the other strings in your program. Generally you can treat it like a global static const variable except it's not accessible outside your function.
It has static storage duration, so it exists throughout the life of the program. Exactly where the compiler/linker put initialized data varies. Returning a pointer to it from a function is fine, but be sure you return a char const *
-- writing to the string causes undefined behavior.
It's been a while since I played with C++, but I remember I (self taught) had a load of problems with strings (well, ok, character arrays...).
If you're going to be modifying their value at all, be sure to use the new and delete keywords... Something along these lines...
char *strText = new char[10];
/* Do something
...
...
...
*/
delete [] strText;
Martin
The string literals are stored on DATA segment and allocated at compile time. This helps to assign same string literals to multiple variables without creating copies of string.
e.g char * str="hello";
The str is char pointer, having address of char h, while "hello" is stored in data segment and cannot be altered. Trying to alter it will generate Segmentation fault.
While assigning a char array string literal creates a copy of string on stack.
i.e char str[]="hello";
"hello" is copied to stack (appended by null character) and str points to character 'h' in stack.
it is packaged with your binary -- by packaged I mean hard-wired, so yes you can return it and use it elsewhere -- you won't be able to alter it though, and I strongly suggest you declare it as:
const char * x = "hello world";