forbiddens in string literals in C

前端 未结 5 688
逝去的感伤
逝去的感伤 2020-12-11 10:00

In the K&R book page 104, I came across this statement:

char amessage[] = \"now is the time\"; //an array
char *pmessage = \"now is the time         


        
5条回答
  •  感动是毒
    2020-12-11 10:26

    If you do this:

    char amessage[] = "now is the time"; //an array
    char *pmessage = "now is the time";  //a pointer
    

    You probably really want to be doing this:

    const char *pmessage = "now is the time";  //a pointer
    

    When your program is compiled, somewhere in memory there will be the bytes "now is the time" (note there is a NULL terminator). This will be in constant memory. You shouldn't try to change it, if you do weird things can result (exactly what will happen will depend on your environment and if it is stored in read-only or read-write memory). So while K&R was trying to enlighten you on how you could do things, the pragmatic way is to make pointers to constant strings const, then the compiler will complain if you try to change the contents.

提交回复
热议问题