0% found this document useful (0 votes)
15 views

Chapter 5

Uploaded by

abebemako302
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Chapter 5

Uploaded by

abebemako302
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Chapter Five

Pointers

1
What is pointer?
• A pointer is a variable which stores the address of another variable.
• The only difference between pointer variable and regular variable is
the data they hold.
• To know the location in the computer memory where the data is
stored, C++ provides the & (reference) operator. The operator
returns the address that a variable occupies.
• For example, if x is a variable, &x returns the address of the variable.

2
Reference operator (&) and Deference operator (*)
• There are two pointer operators in C++:
- & the address of operator
- * the dereference operator
• The reference operator (&) returns the variable's address.
• The dereference operator (*) helps us get the value that has been
stored in a memory address.
• Whenever 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 dereference operator can be
literally translated to "value pointed by”.
For example:
• If we have a variable given the name num, stored in the address 0x234 and storing the value
28.
• The reference operator (&) will return 0x234.
• The dereference operator (*) will return 28. 3
Cont..
• A pointer is simply the address of an object in memory. Generally,
objects can be accessed in two ways: directly by their symbolic
name, or indirectly through a pointer.
• The act of getting to an object via a pointer to it is called
dereferencing the pointer.
• Pointer variables are defined to point to objects of a specific type so
that when the pointer is dereferenced, a typed object is obtained.
• At the moment in which we declare a variable this one must be
stored in a concrete location in this succession of cells (the memory).
• We generally do not decide where the variable is to be placed -
fortunately that is something automatically done by the compiler
and the operating system on runtime, but once the operating system
has assigned an address there are some cases in which we may be
interested in knowing where the variable is stored.
4
Cont..
• This can be done by preceding the variable identifier by an
ampersand sign (&), which literally means, "address of”. For
example:
ptr= &var;
• This would assign to variable ptr the address of variable var , since
when preceding the name of the variable var with the ampersand
( & ) character we are no longer talking about the content of the
variable, but about its address in memory.
• We are going to suppose that var has been placed in the memory
address 1776 and that we write the following:
var=25;
x=var;
ptr = &var;
The result will be the one shown in the following
diagram:

5
Cont..

• We have assigned to x the content of variable var as we have done


in many other occasions in previous sections, but to ptr we have
assigned the address in memory where the operating system stores
the value of var , that we have imagined that it was 1776 (it can be
any address).
• The reason is that in the allocation of ptr we have preceded var
with an ampersand ( & ) character.
• The variable that stores the address of another variable (like ptr in
the previous example) is what we call a pointer.

6
Declaring Pointers
• Is reserving a memory location for a pointer variable in the heap.
• Syntax:
data type * pointer_name ;
• to declare a pointer variable called p_age, do the following:
int * p_age;

Here is an example of valid pointer declarations in C++:


int *x; // a pointer to integer
double *x; // a pointer to double
float *x; // a pointer to float
char *ch // a pointer to a character
• Whenever the dereference operator, *, appears in a variable
declaration, the variable being declared is always a pointer variable.

7
Assigning values to pointers
• p_age is an integer pointer. The type of a pointer is very important.
p_age can point only to integer values, never to floating-point or
other types.
• To assign p_age the address of a variable, do the following:
int age = 26;
int * p_age;
p_age = &age;
OR
int age = 26;
int * p_age = & age;
• Both ways are possible.
• If you wanted to print the value of age, do the following:
cout<<age;//prints the value of age
Or by using pointers you can do it as follows
cout<<*p_age;//dereferences p_age; 8
Cont..
• The dereference operator produces a value that tells the pointer
where to point. Without the *, (i.e cout<<p_age), a cout statement
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 = 13; //assigns a new value to variable age
ü *p_age = 13 //assigns 13 as a value to the memory p_age points at.

ü N.B: the * appears before a pointer variable in only two places:


when you declare a pointer variable and when you dereference a
pointer variable (to find the data it points to).
ü The following program is one you should study closely. It shows
more about pointers and the pointer operators, & and *, than
several pages of text could do.

9
Cont..
#...
#...
int main()
{
int num = 123; // a regular integer variable
int *p_num; //declares an integer pointer
cout<< “num is ”<<num<<endl;
cout<< “the address of num is ”<<&num<<endl;
p_num = &num;// puts address of num in p_num;
cout<< “*p_num is ”<<*p_num<<endl; //prints value of num
cout<< “p_num is ”<<p_num<<endl; //prints value of P_num
}

10
Pointer to void
• Note that we can’t assign the address of a float type variable to an
integer pointer variable and similarly the address of an integer
variable can not be stored in a float or character pointer.
flaot y;
int x;
int *ip;
float *fp;
ip = &y; //illegal statement
fp = &x; //illegal statement
• That means, if a variable type and pointer to type is same, then only
we can assign the address of variable to pointer variable. And if both
are different type then we can’t assign the address of variable to
pointer variable but this is also possible in C++ by declaring pointer
variable as a void as follows:
11
Cont..

void *p;
Let us see an example:
void *p;
int x;
float y;
p = &x; //valid assignment
p = &y; //valid assignment
The difficulty on void pointers is that, void pointers can not
be de referenced. They are aimed only to store address and
the dereference operator is not allowed for void pointers.

12
Pointer and arrays
• Arrays and pointers work based on a related concept. There are
different things to note when working with arrays having pointers.
• The array name itself denotes the base address of the array. This
means that to assign the address of an array to a pointer, you should
not use an ampersand For example:
p = arr;
int numbers [20]; The above is correct since arr represents the arrays'
address. Here is another example:
int * p; p = &arr;
The above is incorrect.
• the following allocation would be valid:
p = numbers;
• At this point p and numbers are equivalent and they have the same
properties, with the only difference that we could assign another value to the
pointer p whereas numbers will always point to the first of the 20 integer
numbers of type int with which it was defined.
• So, unlike p, that is an ordinary variable pointer, numbers is a constant
pointer (indeed that is an Array: a constant pointer).
• Therefore, although the previous expression was valid, the following
allocation is not:
13
numbers = p;
Cont..
• Because numbers is an array (constant pointer), and no values can
be assigned to constant identifiers.
• N.B: An array name is just a pointer, nothing more. The array name
always points to the first element stored in the array. Therefore , we
can have the following valid C++ code:
int ara[5] = {10,20,30,40,50};
cout<< *(ara + 2); //prints ara[2];
• The expression *(ara+2) is not vague at all if you remember that an
array name is just a pointer that always points to the array’s first
element. *(ara+2) takes the address stored in ara, adds 2 to the
address, and dereferences that location.
• Consider the following character array:
char name[] = “C++ Programming”;
• What output do the following cout statements produce?
cout<<name[0]; // ___C__
14
Cont..
cout<<*name; // ___C__
cout<<*(name+3); //_________(the 3rd value is blank space)
cout<<*(name+0); //____C____

#include<iostream>
using namespace std;
int main()
{
int ctr;
int iara[5] = {10,20,30,40,50};
int *iptr;
iptr = iara; //makes iprt point to array’s first element. Or iprt = &iara[0]
cout<< "using array subscripts:\n";
cout<< *(iara + 2); //prints ara[2];

}
Output
30
15
Pointer Arithmetic
• To conduct arithmetical operations on pointers is a little different
than to conduct them on other integer data types. To begin, only
addition and subtraction operations are allowed to be conducted,
the others make no sense in the world of pointers. But both addition
and subtraction have a different behavior with pointers according to
the size of the data type to which they point to.
• When we saw the different data types that exist, we saw that some
occupy more or less space than others in the memory. For example,
in the case of integer numbers, char occupies 1 byte, short occupies
2 bytes and long occupies 4.
• Let's suppose that we have 3 pointers:
c h a r * m y c h a r ;
s h o r t * m y s h o r t ;
long *mylong;
• And that we know that they point to memory locations 1000 , 2000
and 3000 respectively. So if we write 16
Cont..
• And that we know that they point to memory locations 1000 , 2000
and 3000 respectively. So if we write:
m y c h a r + + ;
m y s h o r t + + ;
mylong++;
• mychar , as you may expect, would contain the value 1001 .
Nevertheless, myshort would contain the value 2002 , and mylong
would contain 3004 .
• The reason is that when adding 1 to a pointer we are making it to
point to the following element of the same type with which it has
been defined, and therefore the size in bytes of the type pointed is
added to the pointer.

17
Cont..

This is applicable both when adding and subtracting any number to


a pointer.

18
Pointer and String
• If you declare a character table with 5 rows and 20 columns, each
row would contain the same number of characters. You can define
the table with the following statement.
• Char names[5][20]={{“George”},{“Mesfin”},{“John”},{“Kim”},{“Barbara”}};
• The above statement will create the following table in memory:

• Notice that much of the table is waster space. Each row takes 20
characters, even though the data in each row takes far fewer
characters.
• To fix the memory-wasting problem of fully justified tables, you
should declare a single-dimensional array of character pointers.
Each pointer points to a string in memory and the strings do not
have to be the same length.
19
Cont..
• Here is the definition for such an array:
• c h a r * n a m e [ 5 ] = { { “ G e o rg e ” } , { “ M e s f i n ” } , { “ J o h n ” } ,
{“Kim”},{“Barbara”}};
• This array is a single-dimension array. The asterisk before names
makes this array an array of pointers. Each string takes only as much
memory as is needed by the string and its terminating zero. At this
time, we will have this structure in memory:
• To print the first string, we should use:
• cout<<*names; //prints George.
• To print the second use:
• cout<< *(names+1); //prints Mesfin
• Whenever you dereference any pointer element with the *
dereferencing operator, you access one of the strings in the array.
20
Pointer to pointer
• As the memory address where integer, float or character is stored
in can be stored into a pointer variable, the address of a pointer can
also be stored in another pointer. This pointer is said to be pointer
to a pointer.
• An array of pointer is conceptually same as pointer to pointer type.
• The pointer to pointer type is declared as follows:
Data_type ** pointer_name;
• Note that the asterisk is double here.
int **p; //p is a pointer which holds the
address another pointer.
E.g.:
char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b; 21
Cont..
• This, supposing the randomly chosen memory locations of 7230 ,
8092 and 10502 , could be described thus:

(inside the cells there is the content of the variable; under the cells its location)
• Have a look at the following code:
int main()
{ int data;
int *p1;
int **p2;
data = 15;
cout<< “data = ”<<data<<endl;
p1 = &data;
p2 = &p1;
cout<< “data through p1 = ”<<*p1<<endl;
cout<< “data through p2 = ”<< **p2<<endl;
}
22
THE END OF CH-5

23

You might also like