Chapter 06
Chapter 06
Topic to be covered
Pointer
Array of pointer
Function and pointer
C++ Pointers
pointVar = 0x61ff08
Content of the address pointed to by pointVar (*pointVar) = 5
Changing Value Pointed by Pointers
int var = 5;
int* pointVar;
// Wrong!
// varPoint is an address but var is not
varPoint = var;
// Wrong!
// &var is an address
// *varPoint is the value stored in &var
*varPoint = &var;
// Correct!
// varPoint is an address and so is &var
varPoint = &var;
// Correct!
// both *varPoint and var are values
*varPoint = var;
Pointers and Arrays
• In C++, Pointers are variables that hold addresses of other variables. Not only can a
pointer store the address of a single variable, it can also store the address of cells of an
array.
• Consider this example:
int *ptr;
int arr[5];
• Notice that we have used arr instead of &arr[0]. This is because both are the same.
• The addresses for the rest of the array elements are given by &arr[1], &arr[2], &arr[3],
and &arr[4].
• Suppose we need to point to the fourth element of the array using the
same pointer ptr.
• Here, if ptr points to the first element in the above example then ptr + 3
will point to the fourth element. For example,
int *ptr;
int arr[5];
ptr = arr;
• As we already know, the array name arr points to the first element
of the array. So, we can think of arr as acting like a pointer.
• Similarly, we then used for loop to display the values of arr using
pointer notation.
// &a is address of a
// &b is address of b
swap(&a, &b);
• Here, the address of the variable is passed during the function call rather than the
variable.
• Since the address is passed instead of value, a dereference operator * must be
used to access the value stored in that address.
temp = *n1;
*n1 = *n2;
*n2 = temp;
• *n1 and *n2 gives the value stored at address n1 and n2 respectively.
• Since n1 and n2 contain the addresses of a and b, anything is done to *n1 and *n2
will change the actual values of a and b.
• Hence, when we print the values of a and b in the main() function, the values are
changed.