Ikaa1991
Ikaa1991

Reputation: 29

Why is a dereference " * " operator used in the function name?

I have been currently taking this introductory programming course offered by stanford online, CS106B. In the Linked List structure the professor implemented this code which I am unable to wrap my head around.

 Entry *GetNewEntry(){

    cout << "Enter name (ENTER to quit):";
    string name = GetLine();
    if (name == "") return NULL;
    Entry *newOne = new Entry; // allocate in heap
    newOne->name = name;
    cout << "Enter address: ";
    newOne->address = GetLine();
    cout << "Enter phone: ";
    newOne->phone = GetLine();
    newOne->next = NULL; // no one follows
    return newOne;
}

Can anyone please help me understand why is there an dereference operator before a function name. What would change if we removed that? I have tried to google it but I haven't received any satisfactory answers.

Upvotes: 2

Views: 238

Answers (2)

Dan D.
Dan D.

Reputation: 8557

It's a type called 'pointer to Entry'. It is suggested to put the asterisk next to the type name for easy understanding.

//suggested to put the asterisk next to type name
Entry* GetNewEntry(){...
}

//it's ok to put next to function name too
Entry *GetNewEntry(){...
}

Let's say Entry is a struct, then the size of an Entry variable will be the sum of sizes of properties. However, Entry* is a pointer to an Entry struct, and it is constantly of 4-byte size (32bit system), or 8-byte size (64bit system), whatever the number of properties inside the struct.

Edit: The suggested declaration is easier to understand but it looks wrong in this case:

//a is pointer, b is Entry
Entry* a,b;

Solution is to declare each pointer variable on its own line:

//a is pointer, b is pointer
Entry* a;
Entry* b;

Upvotes: 1

jxh
jxh

Reputation: 70392

The return value of the function GetNewEntry is a pointer of type Entry *.

If you removed the * from the code as is, you would end up returning a Entry instead, and the code would fail to compile, since newOne is a Entry *.

Upvotes: 5

Related Questions