andypf
andypf

Reputation: 197

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

Why does not work this line in prepend()?:

*first = *ent;

I know I could pass first by reference and get it to work, but if I am referencing first and setting that equal to the struct that ent points to why doesn't this work? Even if the pointer vars are passed by value they still point to the same struct?

Upvotes: 0

Views: 81

Answers (2)

Sreekar
Sreekar

Reputation: 1015

*Pointer means the value at address = Pointer. As pointer is currently pointing to garbage you will get a seg fault.

You cannot first dereference "first" because first is pointing to a location in memory that is most probably not of your program's own.

Upvotes: 1

Dominique McDonnell
Dominique McDonnell

Reputation: 2520

What *first = *ent does is copy the data byte for byte pointed at by ent to the location pointed at by first, which in your example will be NULL, and probably cause a seg fault.

What you want is first to be either a reference to a pointer (*&) or a pointer to a pointer (**), so you can change the pointer in the outside function.

For your purposes I suggest reference as it will be easier to read.

So prepend should be (notice I've removed the derefs on the equal line):

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

Upvotes: 1

Related Questions