130 likes | 197 Vues
Pointers. 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.
E N D
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 their values.
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 *yPtr; // declare pointer variable yPtr the statement yPtr = &y; // initialize-assign address of y to yPtr
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.
DEFINING REFERENCES • A reference is another name, or alias, for an object that already exists. • Defining a reference does not occupy additional memory. • Any operations defined for the reference are performed with the object to which it refers.
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
Any Question? • Refer to chapter 1 of the book for further reading