一个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;
} 展开
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;
} 展开
1个回答
展开全部
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){
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了
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询