kmetin
kmetin

Reputation: 263

What is this declaration exactly means as an English sentence?

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

Answers (4)

chacham15
chacham15

Reputation: 14251

First lets get some definitions straight.

  1. Pointer - A number value of an index into memory.
  2. Stack - An area of memory which is responsible for holding the values of local variables
  3. Heap - An area of memory which is responsible for holding long term data.
  4. Compiler - A program which translates code from a programming language into the 1's and 0's that a computer can understand
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

masoud
masoud

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

iehrlich
iehrlich

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

Alok Save
Alok Save

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

Related Questions