Why is my char* writable and sometimes read only in C++

后端 未结 4 1517
天涯浪人
天涯浪人 2020-12-21 09:28

I have had really big problems understand the char* lately. Let\'s say I made a recursive function to revert a char* but depending on how I initial

4条回答
  •  天涯浪人
    2020-12-21 09:50

    char * bob = "hello"; 
    

    This actually translated to:

    const char __hello[] = "hello";
    char * bob = (char*) __hello;
    

    You can't change it, because if you'd written:

    char * bob = "hello"; 
    char * sam = "hello"; 
    

    It could be translated to:

    const char __hello[] = "hello";
    char * bob = (char*) __hello;
    char * sam = (char*) __hello;
    

    now, when you write:

    char * bob = new char[6];    
    bob = "hello\0";
    

    First you assign one value to bob, then you assign a new value to it. What you really want to do here is:

    char * bob = new char[6];    
    strcpy(bob, "hello");
    

提交回复
热议问题