一个c++指针的小问题

voidprint(node*head){cout<<"beginaddress:"<<head<<endl;while(head){cout<<head->data<<... void print(node *head){
cout << "begin address: " << head << endl;
while (head){
cout << head->data << " ";
head = head->next;
cout << "loop address: " << head << endl;
}
cout << "end address: " << head << endl;
cout << endl;
}

int main() {
int a[] = { 1, 3, 4, 6, 7, 3, 8, 2, 1, 0 };
node* head = init(a, 10);
cout << "Main address: " << head << endl;
print(head);
cout << "Main address back: " << head << endl;
return 0;
}
就这么个小问题,有点儿不太明白。
在print里,head一直在变,一直指到最后一位。
为什么主程序调用完print(head)之后,head地址没变啊!!!
#include<iostream>

using namespace std;

struct node {
int data;
node* next;
};

node* init(int a[], int n) {
node* head = nullptr, *p = nullptr;
for (int i = 0; i < n; ++i) {
node* nd = new node();
if (i == 0) {
head = p = nd;
nd->data = a[i];
nd->next = nullptr;
continue;
}
p->next = nd;
nd->data = a[i];
nd->next = nullptr;
p = p->next;
}
return head;
}
展开
 我来答
jhanker
推荐于2016-05-06 · TA获得超过1478个赞
知道小有建树答主
回答量:675
采纳率:73%
帮助的人:476万
展开全部
void print(node *head)中的head和main()函数中的head不是同一个变量,因为只是当在main()函数调用print函数的的时候把main()函数中的head的值复制给void print(node *head)中的head,所以改变print中的head不会改变main()中的head,如果想改变main()中的head把print函数改成下面代码试试:
void print(node **head){
cout << "begin address: " << *head << endl;
while (*head){
cout << (*head)->data << " ";
(*head) = (*head)->next;
cout << "loop address: " <<*head << endl;
}
cout << "end address: " << *head << endl;
cout << endl;
}
调用时用:
print(&head);
更多追问追答
追问
void print(node *head) 这个head传递的是地址嘛?
我试了下。在main里打印出head的地址。
再在print里把head的地址也打印出来。一模一样啊。
追答
是的 两个head都是存储地址的,但事实上一个是实参一个是形参是两个不同的指针变量,就如同 Int *a,*b,c,d; a=b=&c;a=&d;你说这样该变a会不会该变b的值,这里的a,b就相当于print中的head和main中的head了
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式