Cannot modify C string

前端 未结 5 780
小蘑菇
小蘑菇 2020-12-05 16:11

Consider the following code.

int main(void) {
    char * test = \"abcdefghijklmnopqrstuvwxyz\";
    test[5] = \'x\';
    printf(\"%s\\n\", test);
    return EXIT_         


        
5条回答
  •  抹茶落季
    2020-12-05 16:37

    You should get into the habit of matching the type of the variable with the type of the initialiser. In this case:

    const char* test = "abcdefghijklmnopqrstuvwxyz";
    

    That way you will get a compiler error rather than a run-time error. Cranking your compiler warning level up to max may also help avoid such pitfalls. Why this is not an error in C is probably historical; early compilers allowed it and disallowing it might have broken too much existing code when the language was standardised. Now however operating systems do not allow it so it is academic.

提交回复
热议问题