Reference to a pointer

后端 未结 3 806
天命终不由人
天命终不由人 2020-12-01 07:04
char *str = \"Hello\";

char *ptr = str;
char *&rptr = str;

What is the difference between ptr and rptr? I understand rptr is a reference to a

3条回答
  •  伪装坚强ぢ
    2020-12-01 07:18

    Try this:

    #include 
    int main () {
        char *str1 = "Hello ";
        char *str2 = "World!";
        char *ptr = str1;
        char *&rptr = str1;
        rptr = str2;
        std::cout << ptr << str1 << std::endl;
    }
    

    It prints "Hello world!" because ptr is a char pointer pointing to the string literal "Hello ". rptr is a reference to a char pointer, so when you change it (the pointer, not the thing it points at.) you change str1. And thus ptr points to "Hello ". str1 points to "World!".

提交回复
热议问题