小编use*_*284的帖子

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;

}
Run Code Online (Sandbox Code Playgroud)

在c ++中,head是堆栈类的私有或受保护成员,并声明为node*head.

问题:为什么head可以在c ++中调用push()之后保留其值.
在c中,我们需要将其声明为**,因为我们想要在push()函数调用之后更改头指针的值.在c ++代码中,调用后不会改变头部丢失吗?

c c++ pointers data-structures

3
推荐指数
1
解决办法
682
查看次数

标签 统计

c ×1

c++ ×1

data-structures ×1

pointers ×1