Possible Duplicate:
Where are literal strings placed and why can I return pointers to them?
Suppose I have some code like the following:
char *string;
void foo(char *s)
{
string = s;
}
foo("bar");
What is happening internally? Since I have not explicitly declared what I am passing into foo, e.g by doing something like.
char s[] = "bar";
foo(s);
will “bar” always be stored in the same memory location? Does is automatically have some memory allocated for it? If so, does this address remain the same, so that “string” always points to a char array which holds “bar”?
I suppose the more general question I am asking is: What happens internally when you pass an argument to a function without explicitly assigning it into some variable first, and then passing in that variable.
"bar"is a string literal. String literals have static storage duration and their lifetime (as all objects with static storage duration) is the entire execution of the program.So basically there is a
"bar"array object somewhere in your memory at the startup of your program and you are passing a pointer to its first element during the execution of your program which is totally fine.