Can/Why using char * instead of const char * in return type cause crashes?

后端 未结 5 1622
醉梦人生
醉梦人生 2021-01-05 15:12

I read somewhere that if you want a C/C++ function to return a character array (as opposed to std::string), you must return const char* rather than char*. Doing the latter m

5条回答
  •  有刺的猬
    2021-01-05 15:40

    If you have a function that returns "string literals" then it must return const char*. These do not need to be allocated on the heap by malloc because they are compiled into a read-only section of the executable itself.

    Example:

    const char* errstr(int err)
    {
        switch(err) {
            case 1: return "error 1";
            case 2: return "error 2";
            case 3: return "error 3";
            case 255: return "error 255 to make this sparse so people don't ask me why I didn't use an array of const char*";
            default: return "unknown error";
        }
    }
    

提交回复
热议问题