开发者

Storage type of string literal when passed as argument

开发者 https://www.devze.com 2023-04-01 21:49 出处:网络
I\'m curious about string literals. I\'ve read that in the case of something like this,const char * ptr = \"Hello World\"; that t开发者_JS百科hey have static storage duration in the data of the progra

I'm curious about string literals. I've read that in the case of something like this, const char * ptr = "Hello World"; that t开发者_JS百科hey have static storage duration in the data of the program and are not allocated on the heap or stack. What about when it is used as an argument?

for example

Function("panda");

when defined as

void Function(const char* str)
{
...
}

is "panda" now also included in the data of the program or is it allocated on the stack?


Everywhere in your program where you have string constants it's the same. In your example you are just passing a pointer to the address that the string is stored. So it's the same as the general case you presented. Using it as a function argument has nothing to do with where it is stored.


In your example, "panda" is (normally: implementation defined) stored with static duration in the data of the program. When you call Function("panda"), this is the same as extern char* s = "panda"; Function(s);. This is made more clear in your declaration for the function. Function does not receive a char array, it receives a pointer to const chars. So the stack contains a pointer, not a char array.

0

精彩评论

暂无评论...
验证码 换一张
取 消