0% found this document useful (0 votes)
19 views8 pages

C++ Pointers for CS Students

This document provides an introduction to pointers in C++. It discusses that pointers are variables that contain the addresses of other variables rather than holding data directly. It explains that pointers allow accessing and changing data more efficiently than regular variables. The key concepts introduced are pointers, the address of (&) and dereferencing (*) operators, and declaring and initializing pointers. Examples are provided to demonstrate declaring regular variables and corresponding pointer variables, as well as initializing pointers to point to the addresses of other variables.

Uploaded by

nuraddeen212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views8 pages

C++ Pointers for CS Students

This document provides an introduction to pointers in C++. It discusses that pointers are variables that contain the addresses of other variables rather than holding data directly. It explains that pointers allow accessing and changing data more efficiently than regular variables. The key concepts introduced are pointers, the address of (&) and dereferencing (*) operators, and declaring and initializing pointers. Examples are provided to demonstrate declaring regular variables and corresponding pointer variables, as well as initializing pointers to point to the addresses of other variables.

Uploaded by

nuraddeen212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CSC2302 Department of Mathematics and Computer Science

Lecture3: Pointers
C++ reveals its true power through pointer variables. Pointer variables (or pointers, as they generally are
called) are variables that contain addresses of other variables. All variables you have seen so far have
held data values. You understand that variables hold various data types: character, integer, floating-
point, and so on.
Pointer variables contain the location of regular data variables; they in effect point to the data because
they hold the address of the data. When first learning C++, students of the language tend to shy away
from pointers, thinking that pointers will be difficult. Pointers do not have to be difficult. In fact, after
you work with them for a while, you will find they are easier to use than arrays (and much more
flexible).
This chapter introduces the following concepts:
 Pointers
 Pointers of different data types
 The “address of” (&) operator
 The dereferencing (*) operator
 Arrays of pointers
Pointers offer a highly efficient means of accessing and changing data. Because pointers contain the
actual address of your data, your compiler has less work to do when finding that data in memory.
Pointers do not have to link data to specific variable names.
A pointer can point to an unnamed data value. With pointers, you gain a “different view” of your data.
Introduction to Pointer Variables
Pointers are variables. They follow all the normal naming rules of regular, non pointer variables. As with
regular variables, you must declare pointer variables before using them. There is a type of pointer for
every data type in C++; there are integer pointers, character pointers, floating-point pointers, and so on.
You can declare global pointers or local pointers, depending on where you declare them.
About the only difference between pointer variables and regular variables is the data they hold. Pointers
do not contain data in the usual sense of the word. Pointers contain addresses of data.
There are two pointer operators in C++:
& The “address of” operator
* The dereferencing operator
Don’t let these operators throw you; you might have seen them before! The & is the bitwise AND
operator and the * means of course, multiplication.

Page 1
CSC2302 Department of Mathematics and Computer Science

These are called overloaded operators. They perform more than one function, depending on how you
use them in your programs. C++ does not confuse * for multiplication when you use it as a dereferencing
operator with pointers.
Any time you see the & used with pointers, think of the words “address of.” The & operator always
produces the memory address of whatever it precedes. The * operator, when used with pointers, either
declares a pointer or dereferences the pointer’s value. The next section explains each of these
operators.
Declaring Pointers
Because you must declare all pointers before using them, the best way to begin learning about pointers
is to understand how to declare and define them. Actually, declaring pointers is almost as easy as
declaring regular variables. After all, pointers are variables.
If you must declare a variable that holds your age, you could do so with the following variable
declaration:
int age=30; // Declare a variable to hold my age.
Declaring age like this does several things. It enables C++ to identify a variable called age, and to reserve
storage for that variable. Using this format also enables C++ to recognize that you will store only
integers in age, not floating-point or double floating-point data.
The declaration also requests that C++ store the value of 30 in age after it reserves storage for age.
Where did C++ store age in memory? As the programmer, you should not really care where C++ stores
age. You do not have to know the variable’s address because you will never refer to age by its address. If
you want to calculate with or print age, you call it by its name, age.
Suppose you want to declare a pointer variable. This pointer variable will not hold your age, but it will
point to age, the variable that holds your age.
p_age might be a good name for the pointer variable. Figure below illustrates what you want to do. The
figure assumes C++ stored age at the address 350,606. Your C++ compiler, however, arbitrarily
determines the address of age, so it could be anything.

Page 2
CSC2302 Department of Mathematics and Computer Science

The name p_age has nothing to do with pointers, except that it is the name you made up for the pointer
to age. Just as you can name variables anything (as long as the name follows the legal naming rules of
variables), p_age could just as easily have been named house, x43344, space_trek, or whatever else you
wanted to call it. This reinforces the idea that a pointer is just a variable you reserve in your program.
Create meaningful variable names, even for pointer variables.
p_age is a good name for a variable that points to age (as would be ptr_age and ptr_to_age).
To declare the p_age pointer variable, you must program the following:
int * p_age; // Declares an integer pointer.
Similar to the declaration for age, this declaration reserves a variable called p_age. The p_age variable is
not a normal integer variable, however. Because of the dereferencing operator, *, C++ knows this is to
be a pointer variable. Some C++ programmers prefer to declare such a variable without a space after the
*, as follows:
int *p_age; // Declares an integer pointer.
Either method is okay, but you must remember the * is not part of the name. When you later use p_age,
you will not prefix the name with the *, unless you are dereferencing it at the time (as later examples
show).
Consider the declaration for p_age if the asterisk were not there:
C++ would think you were declaring a regular integer variable. The * is important, because it tells C++ to
interpret p_age as a pointer variable, not as a normal, data variable.
Assigning Values to Pointers
p_age is an integer pointer. This is very important. p_age can point only to integer values, never to
floating-point, double floating point, or even character variables. If you needed to point to a floating-
point variable, you might do so with a pointer declared as:
float *point; // Declares a floating-point pointer.

Page 3
CSC2302 Department of Mathematics and Computer Science

As with any automatic variable, C++ does not initialize pointers when you declare them. If you declared
p_age as previously described, and you wanted p_age to point to age, you would have to explicitly
assign p_age to the address of age. The following statement does this:
p_age = &age; // Assign the address of age to p_age.
What value is now in p_age? You do not know exactly, but you know it is the address of age, wherever
that is. Rather than assign the address of age to p_age with an assignment operator, you can declare
and initialize pointers at the same time. These lines declare and initialize both age and p_age:
int age=30; // Declares a regular integer variable, putting 30 in it.
int *p_age=&age; // Declares an integer pointer, initializing it with the address of age.
These two lines produce the value of the variables. If you wanted to print the value of age, you could do
so with the following cout:
cout << age; // Prints the value of age.
You also can print the value of age like this:
cout << *p_age; // Dereferences p_age.
The dereference operator produces a value that tells the pointer where to point. Without the *, the last
cout would print an address (the address of age). With the *, the cout prints the value at that address.
You can assign a different value to age with the following statement:
age=41; // Assigns a new value to age.
You also can assign a value to age like this:
*p_age=41;
This declaration assigns 41 to the value to which p_age points.

Example 1: The following section of code declares three regular variables of three different data types,
and three corresponding pointer variables:
char initial= ‘Q’; // Declares three regular variables
int num=40; // of three different types.
float sales=2321.59;
char *p_initial=&initial; // Declares three pointers.
int * ptr_num=&num; // Pointer names and spacing
float * sales_add = &sales; // after * are not critical.

Page 4
CSC2302 Department of Mathematics and Computer Science

Example 2: Just like regular variables, you can initialize pointers with assignment statements. You do not
have to initialize them when you declare them. The next few lines of code are equivalent to the code in
Example 1:
char initial; // Declares three regular variables
int num; // of three different types.
float sales;
char *p_initial; // Declares three pointers but does
int * ptr_num; // not initialize them yet.
float * sales_add;
initial=’Q’; // Initializes the regular variables
num=40; // with values.
sales=2321.59;
p_initial=&initial; // Initializes the pointers with
ptr_num=&num; // the addresses of their
sales_add=&sales; // corresponding variables.
Notice that you do not put the * operator before the pointer variable names when assigning them
values. You would prefix a pointer variable with the * only if you were dereferencing it.
Keep the data type of each pointer consistent with its corresponding variable. Do not assign a floating-
point variable to an integer’s address. For instance, you cannot make the following assignment
statement:
p_initial = &sales; // Invalid pointer assignment.
because p_initial can point only to character data, not to floating-point data.
Example 3: The following program is an example you should study closely. It shows more about pointers
and the pointer operators, & and *, than several pages of text can do.
// Demonstrates the use of pointer declarations and operators.
#include <iostream.h>
void main()
{
int num=123; // A regular integer variable.
int *p_num; // Declares an integer pointer.
cout << “num is “ << num << “\n”; // Prints value of num.
cout << “The address of num is “ << &num << “\n”;

Page 5
CSC2302 Department of Mathematics and Computer Science

// Prints num’s location.


p_num = &num; // Puts address of num in p_num,
// in effect making p_num point
// to num.
// No * in front of p_num.
cout << “*p_num is “ << *p_num << “\n”; // Prints value of num.
cout << “p_num is “ << p_num << “\n”; // Prints location of num.
return;
}
Here is the output from this program:
num is 123
The address of num is 0x8fbd0ffe
*p_num is 123
p_num is 0x8fbd0ffe
If you run this program, you probably will get different results for the value of p_num because your
compiler will place num at a different location, depending on your memory setup. The value of p_num
prints in hexadecimal because it is an address of memory. The actual address does not matter, however
because the pointer p_num always contains the address of num, and because you can dereference
p_num to get num’s value, the actual address is not critical.
Example 4: The following program includes a function that swaps the values of any two integers passed
to it. You might recall that a function can return only a single value. Therefore, before now, you could
not write a function that changed two different values and returned both values to the calling function.
To swap two variables, you need the ability to pass both variables by address. Then, when the function
reverses the variables, the calling function’s variables also are swapped.
Notice the function’s use of dereferencing operators before each occurrence of num1 and num2. It does
not matter at which address num1 and num2 are stored, but you must make sure that you dereference
whatever addresses were passed to the function.
Be sure to receive arguments with the prefix & in functions that receive by address, as done here.
Identify the program and include the I/O header file. This program swaps two integers, so initialize two
integer variables in main(). Pass the variables to the swapping function, called swap_them, then switch
their values. Print the results of the swap in main().
// Program that includes a function that swaps

Page 6
CSC2302 Department of Mathematics and Computer Science

// any two integers passed to it


#include <iostream.h>
void swap_them(int &num1, int &num2);
void main()
{
int i=10, j=20;
cout << “\n\nBefore swap, i is “ << i <<“ and j is “ << j << “\n\n”;
swap_them(i, j);
cout << “\n\nAfter swap, i is “ << i <<“ and j is “ << j << “\n\n”;
return;
}
void swap_them(int &num1, int &num2)
{
int temp; // Variable that holds
// in-between swapped value.
temp = num1; // The calling function’s variables
num1 = num2; // (and not copies of them) are
num2 = temp; // changed in this function.
return;
}
Arrays of Pointers
If you have to reserve many pointers for many different values, you might want to declare an array of
pointers. You know that you can reserve an array of characters, integers, long integers, and floating-
point values, as well as an array of every other data type available. You also can reserve an array of
pointers, with each pointer being a pointer to a specific data type. The following reserves an array of 10
integer pointer variables:
int *iptr[10]; // Reserves an array of 10 integer pointers
Figure below shows how C++ views this array. Each element holds an address (after being assigned
values) that points to other values in memory. Each value pointed to must be an integer. You can assign
an element from iptr an address just as you would for non array pointer variables. You can make iptr[4]
point to the address of an integer variable named age by assigning it like this:
iptr[4] = &age; // Make iptr[4] point to address of age.

Page 7
CSC2302 Department of Mathematics and Computer Science

The following reserves an array of 20 character pointer variables:


char *cpoint[20]; // Array of 20 character pointers.
Again, the asterisk is not part of the array name. The asterisk lets C++ know that this is an array of
integer pointers and not just an array of integers.
Some beginning C++ students get confused when they see such a declaration. Pointers are one thing,
but reserving storage for arrays of pointers tends to bog novices down. However, reserving storage for
arrays of pointers is easy to understand. Remove the asterisk from the previous declaration as follows,
char cpoint[20]; and what do you have? You have just reserved a simple array of 20 characters. Adding
the asterisk tells C++ to go one step further: rather than an array of character variables, you want an
array of character pointing variables. Rather than having each element be a character variable, you have
each element hold an address that points to characters.
Reserving arrays of pointers will be much more meaningful after you learn about structures in the next
few chapters. As with regular, non pointing variables, an array makes processing several pointer
variables much easier. You can use a subscript to reference each variable (element) without having to
use a different variable name for each value.

LAB PRACTICAL

 Modify the program in Example 4 of your Lecture note to accept inputs from the keyboard.

Page 8

You might also like