The following code is snippet from a FIFO write/read model. The code works. I am only showing the write procedure. My questions are noted after the code snippet.
I have a fundamental question. I have declared the variable HEAD to be of type Ptr. Then I check to see if HEAD = NULL. So, all I have done is declare the variable HEAD. How does that end up pointing to the first node in the list? How does the HEAD = NULL work? Is it that when you declare HEAD, that the NextItem of 'record' Item end up pointing to NULL by default? I haven't allocated memory to HEAD. Nothing. Just the declaration causes it to point to the first node in the list? Don't understand that.
Thanks.
type Item; --Incomplete declaration
type Ptr is access Item;
type Item is record
NextItem : Ptr;
Data : integer;
end record;
variable Head : Ptr;
procedure FIFO_WRITE(Data : in integer) is
variable NewItem : Ptr;
variable Node : Ptr;
begin
NewItem := new Item'(NextItem => Null, Data => Data);
--allocate memory - point to where the Item is stored.
if Head = null then --if the list is empty
Head := NewItem; --claim the memory and initialise Root/Head to the claimed memory.
else
Node := Head; --start with Root node at the beginning of the list
while Node.NextItem /= null loop --Go through linked list and search for
--last/tail node.
Node := Node.NextItem;
end loop;
Node.NextItem := NewItem; --store NewItem(Item) at the tail end of the list.
end if;
end;
I have a fundamental question. I have declared the variable HEAD to be of type Ptr. Then I check to see if HEAD = NULL. So, all I have done is declare the variable HEAD. How does that end up pointing to the first node in the list? How does the HEAD = NULL work? Is it that when you declare HEAD, that the NextItem of 'record' Item end up pointing to NULL by default? I haven't allocated memory to HEAD. Nothing. Just the declaration causes it to point to the first node in the list? Don't understand that.
Thanks.