0% found this document useful (0 votes)
39 views39 pages

C++ Pointers

Pointer variables store memory addresses and can be used to indirectly access and modify the value of another variable. A pointer must be declared with a type (e.g. int*) and is initialized using the address-of operator (&). Pointer arithmetic and dereferencing operator (*) allow manipulating data at the address stored in a pointer. Arrays can also be accessed using pointers by treating array names as pointers to their first element. Multiple levels of indirection are possible but excessive indirection reduces readability. Pointers are commonly used to pass arguments by reference and implement dynamic data structures in C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views39 pages

C++ Pointers

Pointer variables store memory addresses and can be used to indirectly access and modify the value of another variable. A pointer must be declared with a type (e.g. int*) and is initialized using the address-of operator (&). Pointer arithmetic and dereferencing operator (*) allow manipulating data at the address stored in a pointer. Arrays can also be accessed using pointers by treating array names as pointers to their first element. Multiple levels of indirection are possible but excessive indirection reduces readability. Pointers are commonly used to pass arguments by reference and implement dynamic data structures in C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

C++ POINTERS

What are pointers?


• A pointer is an object that contains a
memory address.
• Very often this address is the location of
another object, such as a variable.
• For example, if x contains the address of
y, then x is said to “point to” y.
• Pointer variables must be declared as
such.
The general form of a pointer variable
declaration:
• type*var-name;
• Here, type is the pointer’s base type.
• The base type determines what type
of data the pointer will be pointing
to. var-name is the name of the
pointer variable.
For example:
int *ip;
• Since the base type of ip is int, it can
be used to point to int values.
float *fp;
• In this case, the base type of fp is
float, which means that it can be
used to point to a float value.
The Pointer Operators:
• & is a unary operator that returns the
memory address of its operand. (Recall
that a unary operator requires only one
operand.)
• *, and it is the complement of &. It is a
unary operator that returns the value
of the variable located at the address
specified by its operand.
Unary operators in C/C++
• are operators Types of unary operators:
that act upon a 1. unary minus(-)
single operand 2. increment(++)
to produce a
new value. 3. decrement(- -)
4. NOT(!)
5. Addressof operator(&)
6. sizeof()
unary minus ( - )
– The minus operator changes the sign of its
argument.
– A positive number becomes negative, and a
negative number becomes positive.
– Example:
• int a = 10;
• int b = -a; // b = -10
Increment (++)
• It is used to increment the value of the variable by 1.
The increment can be done in two ways:
– prefix increment
• In this method, the operator precedes the operand (e.g., ++a). The
value of operand will be altered before it is used.
• int a = 1;
• int b = ++a; // b = 2
– postfix increment
• In this method, the operator follows the operand (e.g., a++). The
value operand will be altered after it is used.
• int a = 1;
• int b = a++; // b = 1
• int c = a; // c = 2
Decrement (--)
• It is used to decrement the value of the variable
by 1. The decrement can be done in two ways:
– prefix decrement
• In this method, the operator precedes the operand (e.g., – -
a). The value of operand will be altered before it is used.
• int a = 1;
• int b = --a; // b = 0
– postfix decrement
• In this method, the operator follows the operand (e.g., a- -).
The value of operand will be altered after it is used.
• int a = 1;
• int b = a--; // b = 1
• int c = a; // c = 0
NOT(!):
• It is used to reverse the logical state
of its operand.
• If a condition is true, then Logical
NOT operator will make it false.
–If x is true, then !x is false
–If x is false, then !x is true
Addressof operator(&)
• It gives an address of a variable.
• It is used to return the memory address of a
variable. These addresses returned by the
address-of operator are known as pointers
because they “point” to the variable in
memory.
– & gives an address on variable n
• int a;
• int *ptr;
• ptr = &a; // address of a is copied to the location ptr.
sizeof():
• This operator returns the size of its
operand, in bytes.
• The sizeof operator always precedes its
operand.
• The operand is an expression, or it may
be a cast (casting/converting a pointer).
For example:
ptr = &total;
• puts into ptr the memory address of the variable
total.
• This address is the location of total in the computer’s
internal memory.
• It has nothing to do with the value of total.
• The operation of & can be remembered as returning
“the address of” the variable it precedes.
• Therefore, the preceding assignment statement
could be verbalized as “ptr receives the address of
total.”
• To better understand this assignment, assume
that the variable total is located at address
100.
• Then, after the assignment takes place, ptr has
the value 100.
Assigning Values through a Pointer:

*p = 101;
You can verbalize this assignment like this:
“At the location pointed to by p, assign
the value 101.”

increment or decrement:
(*p)++;
(*p)--;
Pointer Pointer
Arithmetic Comparisons
• ++ • ==
•––
•<
• +
• –.
•>
Pointers and Arrays
char str[80];
char *p1;
p1 = str;
• str is an array of 80 characters
• p1 is a character pointer
• p1 is assigned the address of the first element
in the str array. (p1 will point to str[0]).
• For example, if you want to access the fifth
element in str, you can use:
str[4]
or
*(p1+4)

– Both statements obtain the fifth element.


Remember, array indices start at zero, so when str
is indexed, a 4 is used to access the fifth element.
– A 4 is also added to the pointer p1 to get the fifth
element, because p1 currently points to the first
element of str.
• C++ allows two methods of accessing array
elements: pointer arithmetic and array
indexing.
• This is important because pointer arithmetic
can sometimes be faster than array indexing—
especially when you are accessing an array in
strictly sequential order.
• Since speed is often a consideration in
programming, the use of pointers to access
array elements is very common in C++
programs.
Reversing a string in place: (Activity)
• The program developed here reverses the contents of a string,
in place.
• Thus, instead of copying the string back-to-front into another
array, it reverses the contents of the string inside the array
that holds it.
• The program uses two pointer variables to accomplish this.
One initially points to the beginning of a string, and the other
initially points to the last character in the string.
• A loop is set up that continues to run as long as the start
pointer is less than the end pointer.
• Each time through the loop, the characters pointed to by the
pointers are swapped and the pointers are advanced.
• When the start pointer is greater than or equal to the end
pointer, the string has been reversed.
The process works like this:
• As long as the start pointer points to a memory
location that is less than the end pointer, the loop
iterates.
• Inside the loop, the characters being pointed to
by start and end are swapped.
• Then start is incremented and end is
decremented.
• When end is greater than or equal to start, all of
the characters in the string have been reversed.
• Since both start and end point into the same
array, their comparison is meaningful.
Arrays of Pointers:
• Pointers can be arrayed like any other data
type. For example, the declaration for an int
pointer array of size 10 is
int *pi[10];
• Here, pi is an array of ten integer pointers.
• To assign the address of an int variable called
var to the third element of the pointer array,
you would write:
int var;
pi[2] = &var;
• Remember, pi is an array of int pointers.
• The only thing that the array elements can hold
are the addresses of integer values—not the
values themselves.
• To find the value of var, you would write:
*pi[2]
• Like other arrays, arrays of pointers can be
initialized.
• A common use for initialized pointer arrays is to
hold pointers to strings. Here is an example that
uses a two-dimensional array of character
pointers to implement a small dictionary:
• The program works by testing the word entered
by the user against the strings stored in the
dictionary.
• If a match is found, the meaning is displayed. If
no match is found, an error message is printed.
• Notice that dictionary ends with two null strings.
These mark the end of the array.
• Recall that a null string contains only the
terminating null character. The for loop runs until
the first character in a string is null. This
condition is tested with this expression:
*dictionary[i][0]
Multiple Indirection:
• A pointer to a pointer or a chain of pointers.
• As you can see, in the case of a normal pointer,
the value of the pointer is the address of a value.
• In the case of a pointer to a pointer, the first
pointer contains the address of the second
pointer, which points to the location that contains
the desired value.
• Multiple indirection can be carried on to
whatever extent desired, but there are few cases
where more than a pointer to a pointer is
needed, or, indeed, even wise to use.
• Excessive indirection is difficult to follow and
prone to conceptual errors.
• A variable that is a pointer to a pointer must be declared
as such.
• This is done by placing an additional asterisk in front of
its name.
• For example, this declaration tells the compiler that
balance is a pointer to a pointer of type int:
int **balance;
• It is important to understand that balance is not a
pointer to an integer, but rather a pointer to an int
pointer.
• When a target value is indirectly pointed to by a pointer
to a pointer, accessing that value requires that the
asterisk operator be applied twice, as is shown in this
short example:
Here, p is declared as a pointer to an integer, and q as a pointer to a pointer to an integer. The cout
statement will print the number 10 on the screen.
Sample Machine Problems:
• Write a program that searches an array of
ten integers for duplicate values. Have the
program display each duplicate found.
• Write a program that prompts the user for
two strings and then compares the strings
for equality, but ignores case differences.
Thus, “ok” and “OK” will compare as equal.
• Write a program that counts the uppercase
letters in a string. Have it display the result.
Solution for problem #1:
Solution for problem #2:
Solution for problem #3:

You might also like