About character pointers in C

后端 未结 7 1025
再見小時候
再見小時候 2020-12-11 08:02

Consider this definition:

char *pmessage = \"now is the time\";

As I see it, pmessage will point to a contiguous area in the memory contain

7条回答
  •  死守一世寂寞
    2020-12-11 08:29

    If you define a literal of the form:

    char* message = "hello world";
    

    the compiler will treat the characters as constant and may well put them in read-only memory.

    So, it is advisable to use the const keyword so that any attempt to change the literal will be prevent the program from compiling:

    const char* message = "hello world";
    

    I' guessing the reason const on a literal is not enforced as part of the language is just for backwards compatibility with pre-standard versions of C where the const keyword didn't exist. Anybody know any better?

提交回复
热议问题