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指向爲什麼不工作的結構?即使指針變量是按值傳遞的,它們仍然指向同一個結構體?
你是什麼意思與「不工作」?代碼如你所擁有的,會因爲NULL指針解引用而崩潰,因爲在第一次調用prepend時,listHead爲NULL(所以函數中的first將爲NULL)。 – 1201ProgramAlarm