C++ string literal data type storage

前端 未结 8 1081
一生所求
一生所求 2020-11-30 10:03
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

8条回答
  •  误落风尘
    2020-11-30 10:38

    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.

提交回复
热议问题