Modifying a char *const string

后端 未结 4 1461
别那么骄傲
别那么骄傲 2020-11-28 15:24

I know that const char * is a pointer to a const char, while char *const is a constant pointer to a char. I am testing this in the following code:<

4条回答
  •  孤独总比滥情好
    2020-11-28 16:20

    If you want to test it properly, initialize the strings in a function so the initialization can be dynamic and use strdup() for that.

    int
    main(int argc, char **argv)
    {
        char *d1 = strdup("hello");
        char *d2 = strdup("world");
    
        const char *s = d1;
        char *const t = d2;
    
        ...
    
        free(d1);
        free(d2);
    }
    

    The d1 and d2 variables are mainly used so that the dynamic allocations can be properly freed using free() at the end. Also, as other answers suggest, always treat string literals as const char *.

提交回复
热议问题