结构体指针做参数时注意的问题

在使用结构体指针创建链表的时候,脑子短路,出现低级问题。如下:

首先创建结构体:

#include
using namespace std;

struct node{
    int val;
    struct node* next;
};

如下是创建链表的函数:

/** 
 * @brief: 创建链表
 * @param: 链表头节点指针
 * @ret: void
 * @date: 2022-09-25
 */
void CreateList(node* head) {
    head = (node*)malloc(sizeof(node));
    head->val = 0;
    node* tmp = head;
    for(int i = 1;i < 10;i ++) {
        node* s = (node*)malloc(sizeof(node));
        s->val = i;
        s->next = NULL;
        tmp->next = s;
        tmp = s;
    }
}

如下是主函数中调用CreateList()函数:

int main()
{
    node* head;
    CreateList(head);
    cout << head->val << endl;
    system("pause");
    return 0;
}

这里执行肯定会发生错误的。脑子里一直有个提醒,传指针可以改变原值,于是这里的CreateList(node* head)参数是指针,调用的时候也是传指针,没错,可是参数和调用传的参数它们地位相同,即,都是指针node的指针,那么就相当于值传递了,所以最好的解决办法就是加一个引用,如下,就可以了:

/** 
 * @brief: 创建链表
 * @param: 链表头节点指针
 * @ret: void
 * @date: 2022-09-25
 */
void CreateList(node*& head) {
    head = (node*)malloc(sizeof(node));
    head->val = 0;
    node* tmp = head;
    for(int i = 1;i < 10;i ++) {
        node* s = (node*)malloc(sizeof(node));
        s->val = i;
        s->next = NULL;
        tmp->next = s;
        tmp = s;
    }
}

最后的总结就是:

只要是参数,尽可能传引用,如果不希望改变被引用的对象就用常引用。如下:

#include
#include
using namespace std;

struct node{
    int val;
    struct node* next;
};

/** 
 * @brief: 输出链表的值
 * @param: 链表头节点指针
 * @ret: void
 * @date: 2022-09-25
 */
void PrintList(const node* const &head) {  
    // 希望这个函数中不要改变head和其所指向对象的值
    /* 第一个const防止更改head指向的值,即head->val或head->next 
       第二个const防止head改变被引用对象的值    
    */
    const node* tmp = head;
    tmp = tmp->next;
    while(tmp != NULL) {
        cout << tmp->val << " ";
        tmp = tmp->next;
    }
}

/** 
 * @brief: 创建链表
 * @param: 链表头节点指针
 * @ret: void
 * @date: 2022-09-25
 */
void CreateList(node*& head) {
    head = (node*)malloc(sizeof(node));
    head->val = 0;
    node* tmp = head;
    for(int i = 1;i < 10;i ++) {
        node* s = (node*)malloc(sizeof(node));
        s->val = i;
        s->next = NULL;
        tmp->next = s;
        tmp = s;
    }
}

int main()
{
    node* head;
    CreateList(head);
    PrintList(head);

    system("pause");
    return 0;
}

 

你可能感兴趣的:(c/c++学习笔记,数据结构与算法)