About character pointers in C

后端 未结 7 994
再見小時候
再見小時候 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:25

    String literals in C are not modifiable. A string literal is a string that is defined in the source code of your program. Compilers will frequently store string literals in a read-only portion of the compiled binary, so really your pmessage pointer is into this region that you cannot modify. Strings in buffers that exist in modifiable memory can be modified using the syntax above.

    Try something like this.

    const char* pmessage = "now is the time";
    
    // Create a new buffer that is on the stack and copy the literal into it.
    char buffer[64];
    strcpy(buffer, pmessage);
    
    // We can now modify this buffer
    buffer[1] = 'K';
    

    If you just want a string that you can modify, you can avoid using a string literal with the following syntax.

    char pmessage[] = "now is the time";
    

    This method directly creates the string as an array on the stack and can be modified in place.

提交回复
热议问题