Why is it possible to assign a const char* to a char*?

后端 未结 5 1980
粉色の甜心
粉色の甜心 2021-01-04 03:27

I know that for example \"hello\" is of type const char*. So my questions are:

  1. How can we assign a literal string like \"hel

5条回答
  •  执笔经年
    2021-01-04 04:09

    The answer to your second question is that the variable s is stored in RAM as type pointer-to-char. If it's global or static, it's allocated on the heap and remains there for the life of the running program. If it's a local ("auto") variable, it's allocated on the stack and remains there until the current function returns. In either case, it occupies the amount of memory required to hold a pointer.

    The string "Hello" is a constant, and it's stored as part of the program itself, along with all the other constants and initializers. If you built your program to run on an appliance, the string would be stored in ROM.

    Note that, because the string is constant and s is a pointer, no copying is necessary. The pointer s simply points to wherever the string is stored.

提交回复
热议问题