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 the stack class and is declared as node * head.

Question: why the head can retain its value after calling push () in C ++.
In c, we need to declare it as **, since we want to change the value of the head pointer after calling the push () function. In C ++ code, won't the changes in the head be lost after the call?

+3
source share
2 answers

The problem here is that the C code you are comparing with C ++ is actually not the same. Best example:

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;  
}

push ** . , Stack*. , ++. ++ this .

+7

, Stack::push , head this->head. , head = newNode :

this->head = newNode;
+3

All Articles