Simple pointer declaration
Understanding how pointer variable is a notation for address of an entity in memory.
Learning Objectives
- Understanding declaration of a pointer type variable.
- Understanding use of address of (&) operator.
- Understanding use of * as de-referencing for reading value of a pointer variable.
Source Code
Run Output
Code Understanding
int a=10;
This is normal way of variable declaration
int *p=&a;
Here we have declared p with an asterisk which denotes that it contains an address of memory place which is meant to store an integer value. We assign address of a (&a) to p the pointer type variable.
cout<<p<<endl;
Since p is pointer variable so it will contain memory address. The address value show here will be different for different run occasion and different systems as it would be allocated only when the new pointer variable is declared.
cout<<*p<<endl;
This will print 10 contain in the pointer variable p. *p denotes the value at pointer variable p. Remember that at the time of declaration * denotes the type of variable and at the time use it denotes the value at given location.
Notes
- For more detailed understanding of pointers in general students can visit the following links.
https://en.wikipedia.org/wiki/Pointer_(computer_programming)
http://www.cplusplus.com/doc/tutorial/pointers/ - Pointer declaration syntax options are.
int *p; //* as prefix of variable name
int* p; //* as suffix of data type - The * before pointer variable when it is being used (for example when value is being printed) is also called the de-referencing operator
Suggested Filename(s): ptr.cpp, simp-ptr.cpp