Sunteți pe pagina 1din 8

Riphah International University

Faculty of Computing
Programming Fundamentals (Spring 2016)
Lab 16: C++ Pointers
Lab Objective:
In this lab, you will:
See the definition of a pointer.
Observe the basic pointer operators.
See mechanism for simple pointer manipulation.

Definition of a Pointer.
Pointers are a type of variable that allow you to specify the address of a variable. They provide
a convenient means of passing arguments to functions and for referring to more complex data
types such as structures. They are also essential if you want to use dynamic data in the free
store area. (That was a free look ahead to the dynamic data topic covered later in these notes.)
You won't always know the specific value in a pointer, but you won't care as long as it contains
the address of the variable you are after. You need to declare and initialize pointers just as you
would other variables, but there are special operators that you need to use.

Pointer Operators.
Here is a table showing the special characters used in C++ to declare and use pointers.

dereference
operator,
indirection
operator

&

reference
operator,
address-of
operator

This is used to declare a variable as a pointer.


It is also used when you want to access the value pointed to by the
pointer variable.
Use before a variable to indicate that you mean the address of that
variable. You'll often see this in a function header where the
parameter list is given.

Simple Pointer Use.


We'd better look at some examples to make this clear.
First, we'll declare two ordinary integers, and also pointers to those integers.
Int alpha =
5; Int beta =
20;
int* alphaPtr = α
int* betaPtr = β

The characters Ptr in the pointer variable name have no special significance. They are simply
a memory aid for the programmer. Let's look more closely at one of the pointer declarations.
int*alphaPtr = α

The first part int*, tells


the compiler to declare a
pointer for integers.
alphaPtr will be the name
of that pointer. In the last
part of that statement,
α specifies that the
address of the variable alpha is what should be assigned to the pointer variable.

An aside here: It is also permissible to position the asterisk closer to the pointer variable
name, i.e. int *alphaPtr. However the convention seems to be moving towards placing the
asterisk closer to the datatype.

Try to visualize memory after these declarations, thinking of the pointer variable as not having
a particular value, simply links to the variables to which they had been assigned.

Now let's look at a trivial


example of how to
access this data.
*alphaPtr += 5;
*betaPtr += 5;

After these statements, it is only the contents of the alpha and beta variables that would
be changed.
You might say, "What's the big deal here? I could just as easily have written this:"

alphaPtr += 5;
betaPtr+= 5;
True, but typically pointers aren't used in such a simple manner. We just showed this to
illustrate the use of pointer syntax.

Char Pointer
A variable of type pointer to char can be initialized with a string literal
For example
char *pSentence = Practice makes a man perfect;
This statement creates a null-terminated string literal from the character string
appearing in the quotes
It stores the address of the first character of the string literal in pSentence the pointer
You can also declare an array of pointers using characters.
#include <iostream>
using namespace std;
int main()
{
int choice = 0;
char *pStudent [] =

{"Muhammad Ahsan",
"Kamran Ahmed",
"Asad Sana",
"Noor Khan",
"Adeel Shahzad",
"UmerArif"
};

char *pStr = "Your Favorite Student is";


cout<<endl
<<"Enter a number between 1 and 6"
<<endl;
cin>>choice;

if (choice >= 1 && choice <= 6)


{
cout<<pStr<<" "<<pStudent[choice -1]
<<endl;
}//end if else
{
cout<<"Sorry, you haven't got a Favorite Student"
}

<<endl;

return 0;
}

Null pointer
A pointer should be set to zero when it is not assigned to a valid address. Such a pointer is
called a null pointer. Doing this will allow you to check whether the pointer can be safely
dereferenced, because a valid pointer will never be zero.
For example, although the previous pointer has had its memory released, its stored address
still points to a now inaccessible memory location. Trying to dereference such a pointer will
cause a run-time error. To help prevent this, the deleted pointer should be set to zero. Note
that trying to delete an already deleted null pointer is safe. However, if the pointer has not
been set to zero, attempting to delete it again will cause memory corruption and possibly crash
the program.
delete d; d =0;// mark as null
pointer delete d;// safe

Since you may not always know whether a pointer is valid, a check should be made whenever a
pointer is dereferenced to make sure that it is not zero.
if(d !=0){*d =10;}// check for null pointer

The constant NULL can also be used to signify a null pointer. NULL is typically defined as zero in
C++, making the choice of which to use a matter of preference. The constant is defined in the
stdio.h standard library file, which is included through iostream.
#include<iostream>
//
if(d !=NULL){*d =10;}// check for null pointer

Pointers and Arrays


In C, there is a strong relationship between pointers and arrays. Any operation that can be
achieved by array subscripting can also be done with pointers. Understand the below sequence
of tasks*:

Now try the following :


>>>intb[5];

>>>b[0] = 10;
>>>b[0];
>>>*b;
>>>b;
Here, we see that b[0] stores 10 like we would expect. *b also returns the value 10. This is
because in C arrays are generally stored as pointers to places in memory. Thus, the dereference
of b yields the integer value in b[0]. We confirm that this is defined like a pointer by using ccons
to output b;

Manipulating Pointers
So far, we have used pointer by first initializing them to a variable; however, we can also do
arithmetic with pointers to change the memory address that they point to. This is easiest to see
when working with arrays because the compiler will store the values of an array in subsequent
memory locations. This can be seen in the following code:

#include<stdio.h>
intmain()
{
intiray[5];
int* ipoint = &iray[0];
for(inti = 0; i < 100; i++)
{
*ipoint = i;
Cout<<* ipoint;
ipoint = ipoint +1;
}

for(inti = 0; i < 5; i++)


{
Cout<<iray[i];
}
return0;
}

The above code just initializes the array iray with the values 0-4 same as the code in the first
section; however, it does it by incrementing a pointer to point to the entire array. The
program also prints out the address in memory of the array elements as it runs. Note that
each time ipoint is incremented, the actual address is changed by 4 bytes. This is because
each time the pointer is incremented it is meant to point to the next integer in memory and
here an int is 4 bytes. Thus, the pointed is incremented by four.

Lab Tasks:

Write a program that dynamically allocates an array of integers.

Write a program that dynamically allocates an array large enough to hold the test scores
of a class. Input the scores from user. Also calculate the average test marks and
deallocate the newly allocated memory.

Write a program that dynamically creates an array of double. Input the values from user
and display. After that the program should create a copy of array and store the
elements of first array in new array in reverse order.

S-ar putea să vă placă și