链表函数cpp中的指针作用域

Pointer scope in linked list function cpp

struct Entry {
    std::string name, phone;
    Entry *next;
};

Entry * getNewEntry() {
    std::cout << "Enter name (RETURN to quit): ";
    std::string name;
    std::getline(std::cin, name);
    if (name == "") return NULL;
    Entry *newOne = new Entry; //allocates a new entry struct obj in the heap
    newOne->name = name;
    std::cout << "Enter phone number: ";
    std::string number;
    std::getline(std::cin, number);
    newOne->phone = number;
    newOne->next = NULL; //in this function pointer to next entry is NULL
    return newOne;
}

void prepend(Entry *ent, Entry *first) {
    ent->next = first;
    *first = *ent;
}

Entry * buildAddressBook() {
    Entry *listHead = NULL;
    while (true) {
        Entry *newOne = getNewEntry();
        if (!newOne) break;
        prepend(newOne, listHead);
    }
    return listHead;
}

为什么这条线在 prepend() 中不起作用?:

*first = *ent;

我知道我可以先通过引用传递并让它工作,但如果我先引用并将其设置为等于 ent 指向的结构,为什么这不起作用?即使指针变量按值传递,它们仍然指向相同的结构?

*first = *ent 所做的是将 ent 指向的字节的数据字节复制到 first 指向的位置,在您的示例中将为 NULL,并且可能导致段错误。

你首先要的是要么是对指针的引用(*&),要么是对指针的指针(**),这样你就可以在外部函数中改变指针。

出于您的目的,我建议参考,因为它更容易阅读。

所以前置应该是(注意我已经删除了相等行上的 derefs):

void prepend(Entry *ent, Entry *&first) {
    ent->next = first;
    first = ent;
}

*Pointer 表示地址= Pointer 处的值。由于指针当前指向垃圾,您将遇到段错误。

您不能首先取消引用 "first",因为首先指向的是内存中的一个位置,而该位置很可能不属于您的程序。