Pointers 1 Each cell can be easily located
Pointers 1
� Each cell can be easily located in the memory because it has a unique address. Reference operator (&) � The address that locates a variable within memory is what we call a reference to that variable. � This reference can be obtained by preceding the identifier of a variable with an ampersand sign (&), known as reference operator. �Note that using the address/refrence operator, &, for a given object creates a pointer to that object. �Example: given that var is an int variable, &var is address of the object var
Dereference operator (*) �A variable which stores a reference to another variable is called a pointer. �Using a pointer we can directly access the value stored in the variable which it points to. �To do that, precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be translated to "value pointed by".
Pointer variable declaration and initialization �A pointer is an expression that represents both the address and type of another object. �Any pointer is placed during runtime in the specific memory address. �An expression such as &var is a constant pointer; however, C++ allows you to define pointer variables, that is, variables that can store the address of another object. �In a declaration, the star character * always means “pointer to. ” � Example: int *ptr; �Pointer variables contain memory addresses as
�After declaring a pointer variable, you must point the pointer at a memory address by using the address operator. �Example : int y = 5; // declare variable y int *y. Ptr; // declare pointer variable y. Ptr the statement y. Ptr = &y; // initialize-assign address of y to y. Ptr
Example 6
7
Indirection operator �The indirection operator(dereference operator) * is used to access an object referenced by a pointer: �Given a pointer, ptr, *ptr is the object referenced by ptr. �Example: long a = 10, b, *ptr; ptr = &a; // Let ptr point to a. b = *ptr; �Note : The indirection operator * has high precedence, just like the address operator &. Both operators are unary.
9
References
DEFINING REFERENCES �A reference is another name, or alias, for an object that already exists. �Defining a reference additional memory. does not occupy �Any operations defined for the reference are performed with the object to which it refers. 11
�The ampersand character, &, is used to define a reference. Given that T is a type, T& denotes a reference to T. �Example: float x = 10. 7; float& rx = x; //The place contents the value 10. 7. have two names and one address. cout<<x<< endl; //output: 10. 7 cout<<&x<<endl; //address of x in memory cout<<rx<< endl; // output: 10. 7 cout<<&rx<< endl; //address of x in memory = &x 12
Any Question? �Refer to chapter 1 of the book for further reading
- Slides: 13