开发者

pointer operation in c & c++

struct node {

    int data;
    struct node* next;

}

void 开发者_运维百科push (struct node **head, int data) {

    struct node* newNode = malloc (sizeof (struct node));
    newNode->data = data;
    newNode->next = *head;
    *head = newNode;     
} 

//I understand c version well.

C++ version

void Stack::push( void *data ) {

        struct node *newNode = new node;
        newNode->data = data;
        newNode->next = head;
        head = newNode;

}

In c++ head is a private or protected member of stack class and is declared as node *head.

Question: why head can preserve its value after push() call in c++.

In c, we need to declare it as ** since we want to change the value of head pointer after the push() function call. In c++ code, won’t changes to head be lost after the call?


The problem here is the C code you're comparing to C++ is not really analogous. A better example would be

typedef struct Node { 
  int data;
  struct Node* pNext;
} Node;

typedef struct Stack {
  Node* pHead;
} Stack;

void push(Stack* this, int data) {
  Node* newNode = malloc (sizeof (Node));
  newNode->data = data;
  newNode->next = this->head;
  this->head = newNode;  
}

In this version we've successfully implemented push without having to take a ** for head. We have in a way because it's double indirected via the Stack*. But this is very similar to how C++ works. It's possible to view C++ as passing this as a hidden argument to the function.


In this case, since Stack::push is non-static, head is a shorthand for this->head. So the head = newNode is the same as:

this->head = newNode;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜