分配后可以改变价值吗?

时间:2017-06-26 12:21:47

标签: c++ reference linked-list

我对这个问题感到困惑,并且不知道如何问这个问题。 喜欢if -

current = head;

如果" head"的价值稍后更改

head = temp->next;

将"当前"的价值也改变了?

2 个答案:

答案 0 :(得分:4)

这取决于git clone <upstream-repo-url/repo.git> --mirror git remote add <your-remote-name> <your-remote-url/repo.git> git push <your-remote-name> --mirror (以及current)的类型

例如,在:

head

Node *head = get_head_from_somewhere(); Node *&current = head; head = head->next; 别名current,因此更改head(将其推进到指向下一个节点)也会影响head。它们都具有相同的值。

事实上,虽然他们都在上面声明的范围内,current将永远成功。

然而

assert(head == current)

创建一个新的独立指针,它只是指向与Node *current = head; 相同的位置。推进head不会在此处更改head

答案 1 :(得分:3)

答案是(除非您使用references);如果头部的值发生变化,则当前的值不会改变。

然而;如果current和head是指针,那么引用的值可能会改变。例如:

int a = 4;
int *a1 = &a;
int *a2 = a1; // now both pointers a1 and a2 have the same value (ie the address of integer a) AND point to the same value (4)
*a1 = 5; // change value of a using pointer a1
printf("%i\n", *a2); // will print 5 since a2 also points to integer a and its value has thus changed. The value of a2 itself has not changed though (still pointing to the address of a)