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 return it from inside of the function body?
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 return it from inside of the function body?
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";
The string is stored in the data area of the program. This is completely compiler, executable format, and platform dependent. For example, an ELF binary places this in a different location than a Windows executable, and if you were compiling for an embedded platform this data might be stored in ROM instead of RAM.
Here's an illustration of the layout of the ELF format:
Your string data would most likely be found in the .data
or .text
sections, depending on compiler.
You can certainly return it from inside the function body. Just check with your implementation to verify that it is random access, as many implementations won't let you overwrite it.
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 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!
§2.14.15 String Literals, Section 7
A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration.
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