Reputation: 263
if i write this code:
Node* head;
I understand head is a variable type of Node and it stores a variable's address type of Node.
Is that true?
Upvotes: 0
Views: 195
Reputation: 14251
First lets get some definitions straight.
Node *head;
What this does is allocate space on the stack for a pointer. Note that only the space for the pointer is allocated, not space for the data. Now Node
is the type. That tells the compiler what data is at that location. It also tells the compiler how to interact with the data.
Node *head = new Node();
This allocates space for the pointer on the stack. It then allocates space in the heap and returns the address (the index) to be stored in the space on the stack. Remember that data on the stack disappears after the function returns, so if you don't call delete
to get rid of the data in the heap or pass the reference on, when the function returns you have no way to access the data or delete it; this is called a memory leak.
Node head;
This declaration, however, allocates space for all of the data for the Node object on the stack. The main difference between this and the allocation to the heap (one example above) is that this variable is LOCAL. I.e. it will disappear after the current function returns.
Upvotes: 2
Reputation: 56509
head
is a pointer to memory with format of Node
.
Pointer is a variable that stores a memory address.
http://www.cplusplus.com/doc/tutorial/pointers/
The memory of your computer can be imagined as a succession of memory cells, each one of the minimal size that computers manage (one byte). These single-byte memory cells are numbered in a consecutive way, so as, within any block of memory, every cell has the same number as the previous one plus one.
Upvotes: 1
Reputation: 3592
Node *head
is what you wrote, here *head
is a "variable" of type Node and head is a reference to it.
When you dereference head (doing *head) you obtain your variable.
Upvotes: -3
Reputation: 206566
Node* head;
It means create a variable by name head
which can store the address of another variable of data type Node
.
In simple words, head
is a pointer of the type Node
.
Also, you should never use uninitialized pointers like this always initialize them when you create them.
Node* head = NULL;
Upvotes: 4