【发布时间】:2014-10-31 19:10:50
【问题描述】:
传递指针基本上就像将指针作为值传递..函数内部对指针的更改不会修改指针的实际值..但是当我们需要在函数中访问实际指针本身时,那么我们就提出了指向指针的概念。这是我的理解..
struct node
{
int data;
struct node* next;
};
void push(struct node** head_ref, int new_data) // i understand the need of pointer to pointer here, since we are changing the actual value by adding a node..
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void insertAfter(struct node* prev_node, int new_data) // why are we not using pointer to pointer here since even here the pointer data is getting modified..??
{
if (prev_node == NULL)
{
return;
}
struct node* new_node =(struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
int main()
{
struct node* head = NULL;
append(&head, 6);
insertAfter(head->next, 8);
return 0;
}
请澄清.. 我很困惑为什么我们没有在 InsertAfter(...) 中使用指向指针的指针,以及认为我们在那里更改了指针?
【问题讨论】:
-
在 C++ 中,不要在每次引用
struct时重复struct。另外,一般不要使用malloc。将构造函数添加到struct或class类型后,这一点很重要。 -
"但是当我们需要在函数中访问实际指针本身时,我们就提出了指向指针的概念。这是我的理解.."这基本上是正确的,如果要从函数中更改指针值,则需要指向指针或引用指针的指针。虽然它看起来更像你怀疑或你的代码有一些问题。您对此有什么特别的疑问吗?
-
是的..我把我的疑问放在代码中作为代码本身的注释..我想知道为什么 insertAfter(...) 没有指针?指向指针虽然它是变化的指针的值......为什么他们自己维护单指针概念......
标签: c++ pointers linked-list pointer-to-pointer