Declaration of Pointers-Introduction To Programming-Lecture Notes, Study notes of Computer Programming

A program is a precise sequence of steps to solve a particular problem. This course includes basic programming structure like loops, operator, memory allocation, reference, pointers etc. It teaches how to be a good programmer. This lecture handout is about: Declaration, Pointers, Bubble, Sort, Call, Reference, Locate, Address, Memory, Location, Address, Assign, Value, Statement, Representation

Typology: Study notes

2011/2012

Uploaded on 08/06/2012

anchal
anchal 🇮🇳

4.6

(9)

95 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture No. 14
143
MaterialReading
eitel - C++ How to Program
Chapter 5
5.1, 5.2, 5.3, 5.4,
1) Pointers
2) Declaration of Pointers
Example 1 (Bubble Sort)
Pointers and Call By Reference
5) Example 2
the earlier lectures, we had briefly referred to the concept of pointers.
et’s see what a pointer is and how it can be useful.
emory address is
contain a memory address, not the value of the variable.
e following
ne to take a parcel to the house of a
erson, named Ahmad. Here the point of reference is a name.
f we specifically tell him the number of house and the street
umber. Then this is a reference by the address of the house. It means
that we have two ways to locate an address. To understand further the
oncept of memory address, the example of the computers can be
helpful. In computers, one can have a name x which is associated with
y 6000 or
sses interchangeably to refer to memory locations. When a value
is referred by a normal variable is known as direct reference. While the
Deitel & D
5.5, 5.6
Summary
3)
4)
Pointers
In
L
Pointers are a special type of variables in which a m
stored. They
The concept of the pointers can be well understood from th
example.
Suppose, we request someo
p
However, i
n
c
a memory location. We can have the memory address of x, sa
whatever it is. So the simple variable names are those of specific
locations in memory. But in terms of addresses, these are the
addresses of those memory locations. We can use these names and
addre
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Declaration of Pointers-Introduction To Programming-Lecture Notes and more Study notes Computer Programming in PDF only on Docsity!

Lecture No. 14

Reading Material

eitel - C++ How to Program Chapter 5 5.1, 5.2, 5.3, 5.4,

  1. Pointers
  2. Declaration of Pointers Example 1 (Bubble Sort) Pointers and Call By Reference
  3. Example 2

the earlier lectures, we had briefly referred to the concept of pointers. et’s see what a pointer is and how it can be useful.

emory address is contain a memory address, not the value of the variable. e following

ne to take a parcel to the house of a erson, named Ahmad. Here the point of reference is a name. f we specifically tell him the number of house and the street umber. Then this is a reference by the address of the house. It means that we have two ways to locate an address. To understand further the oncept of memory address, the example of the computers can be helpful. In computers, one can have a name x which is associated with y 6000 or

sses interchangeably to refer to memory locations. When a value is referred by a normal variable is known as direct reference. While the

Deitel & D

5.5, 5.

Summary

Pointers

In L

Pointers are a special type of variables in which a m stored. They The concept of the pointers can be well understood from th example.

Suppose, we request someo p However, i n

c

a memory location. We can have the memory address of x , sa whatever it is. So the simple variable names are those of specific locations in memory. But in terms of addresses, these are the addresses of those memory locations. We can use these names and addre

docsity.com

on is with reference to the address of that memory location. In other words, ‘assign a value to the

are d to refer the values at those addresses.

Following figure shows directly and indirectly referencing a variable.

a variable whose val

xptr indirectly references a variable whose value is 10 xptr x

value referred through the use of memory address may be known as indirect reference.

To understand further the terms of direct reference and indirect reference, suppose that we want to assign a value 10 to x. This can be done by writing x = 10. In this statement, the value 10 will be assigned to the memory location which has label (name) x. The second way to assign a value to a memory locati

memory location whose address is contained in the variable (that is a pointer) on right hand side of the assignment operator’. Operators used to refer the address of memory locations an

x directly references

ue is 10 x

ow we will try to comprehend the concept with another daily life example. Suppose, hundreds of people are sitting in an auditorium. The ost is for a person amongst the audience. here re tw met zewinner to dais. The host can the number of the seat. These are quiva ent to ‘call by name’ and ‘call by address’ methods. In both ases the p ze wi to a person whether he is called by ame or referred by address (seat number in this case). In programming, pointers are used to refer by the addresses.

inter to a character and so on. It

10

10

N

h going to announce a prize T a o hods to call the pri either call the name of the person or e l c , ri ll be delivered n

Declaration of Pointers

Pointers work by pointing to a particular data type. We can have pointer to an integer, pointer to a double, po

docsity.com

ow w derstand what address a pointer holds. Suppose, we declare a pointer variable ptr and a variable x and assign a value 10 it. We write this as under.

Here x is a name of a memory location where a value 10 is stored. We

into the pointer ptr. To get the address of x , we use address operator ddress of x pointer ptr , we write

x

N e will try to un

to

int *ptr ;

int x ;

x = 10 ;

want to store the address of this memory location (which is labeled as x )

i.e. &. (it is & not &&, the && is logical AND). To assign the a to

ptr = &x ;

This statement assigns the memory address of the location x to the pointer ptr. The following figure shows a schematic representation of memory after the preceding assignment is executed.

ptr

The pointers contain whole numbers as they contain memory addresses. An address can be represented

1

only in whole numbers. Therefore, a pointer is a whole number, sufficient enough, to hold any memory address of the computer. The pointers have no specific data type.

docsity.com

we have a pointer to a memory location. Now, it can be ascertained what value is stored in that memory at a memory address, we use the by asterisk (*). The * is used with lue stored at that address. To get e value stored at the memory address ptr , we write * ptr which is read s the value of whatever ptr points to. Thus the line z = *ptr; means, z

ptr

Address: 500000 400000

In the above assignment statement,

location. To get the value stored dereferencing operator, represented the name of the pointer to get the va th a has the value of whatever ptr points to.

The following example can explain the representation of the pointer in memory. Assume that variable x is stored at location 400000 and pointer variable ptr is stored at location 500000.

x 400000 10

We can use this operator (*) to get any arithmetic operation with it. The following m make it further clear.

the value and can do state ents

z = *ptr + 2 ;

ere *ptr giv mory address where the pointer

ng practice to initialize a variable re that there will be no unknown value e later stage.

z = *ptr * 2 ;

z = *ptr – 2 ;

H es the value stored at me ptr points to.

We know that it is a good programmi when we declare it. This will ensu in the variable at som

docsity.com

is statement describes that the value entered through the keyboard s wherever the

lue soci we write *num and &num the address. This thing can be summarized as follows

ints to and

dres of the variable num

ers the left hand side exactly like ordinary u would have an address statement on the (operator (&) ) cannot be of an expression. alway le variable. We cannot write &(x+y). The ) would be either of x (&x) or of y (&y). The address operator (&) operates on a simple variable. Precisely speaking, whenever we a pointer on left hand side, the right hand side should have an er appears on the right hand side of an expression, it n participate in any expression. In this case, we use the operator * ith the pointer name and get the value stored where the pointer points

. Obviously we can do any calculation with this value (i.e. it can be

ubble Sort)

knowing the technique of bubble sorting. Its application helps us compare two values each time and interchange the larger and ler values. In this way, we sort the arrays. To interchange the position of larger and smaller value, the technique of swapping is used. common in programming. While using this technique, mporary location to preserve it and e of second variable to the first. Then the temporary to the second variable.

se, we want to swap the values of two variables x and y. For this se, a third variable temp is used in the following fashion.

cin >> *num ;

Th (as cin is used) will be stored at the memory addres pointer num is pointing to.

While using va as ated with the pointer, in case of using

*num means the value of whatever the num po

&num means the ad s

The point can appear on variables. In this case, yo right hand side. The address Rather, it is s of a simp address (&

have address. If a point ca w to used in any expression).

Example (B

You might be

smal

Swapping is very we put value of one variable in a te assign the valu value is assigned

Suppo purpo

docsity.com

temp = x ;

x = y ;

program to swap the the question arises, can we call a function swap (x, y) which has a code to swap the values of x and y. We call the ontrol comes back to the lues of x and y are the same as before. These are not swapped. This is mainly due to the fact that passing value to ange the values in the wap function receives a copy of the values and inal values remain the

a call by reference to To write the swap function ues always use pointers in the function to get the wapped values in the calling function. The code fragment in our main rogram will be written as follows:

yptr = &y ; // address of y is stored in

of swap function will be:

y = temp ;

We can write the above three statements in a value of x and y. Now

function swap by passing x and y. When the c calling function, the va

function swap is a call by value. It does not ch calling function. The s interchanges the values in that copy. The orig same.

To interchange two values in a function, we make the function. Here comes the use of pointers. to interchange two val s p

yptr

xptr = &x ; // address of x is stored in xptr

swap (yptr, xptr) ; // addresses are passed

The receiving function must know that addresses are being passed to it. So the declaration

swap (int *yptr, int *xptr)

{

… … …

}

docsity.com

if ( x[j] > x[j+1]) // compare two values and interchange if needed

{

swap(&x[j],&x[j+1]);

displ y the ach comparison

for (j=0; j<10; j++)

function using pointers to interchange the values

if(*x > *y)

*y = tmp;

swaps++;

// a array’s elements after e

cout << x[j] << '\t';

cout << endl;

if (swaps == 0)

break;

}

}

void swap(int *x, int *y) //

{

int tmp;

tmp = *x;

*x = *y;

docsity.com

Following is the output of the program of bubble sort.

Pointe

ction that performs a specific task again and ach time. One way to do this is to

le variable in the pointer variable d pass it to the function. This is a call by reference. Thus the same ointer variable can be used each time by assigning it the address of a ifferent variable.

all a

sed with in the function. In call by value mechanism, the values of ese variables are written somewhere else in the memory. That means f these values is made. Then control goes to the called function nd this copy of values is used in the function. If we have to pass a

bers of values. In such cases, it is better to pass the reference

rs and Call By Reference

Suppose, we have a fun again but with different variables e pass a different variable to the function, each time, by reference. We can also write the function with pointers. In this case, before calling the function, put the address of the simp an p d

The mechanism behind calling a function is that, when we c function we pass it some variables. The values of these variables are u th a copy o a huge number of values to a function, it is not advisable to copy these huge num

docsity.com

he use of keyword const in declaration statement is a little tricky. The statement

int *const myptr = &x ;

to integer. But if we change the

*myptr = &x ;

This s e is a pointer to a constant integer. This means that the value of pointer myptr can be changed but the ue stored at that location cannot be changed. This declaration is seful. It has a common use in call by reference mechanism. When we guments to a function by reference without changing red at that addresses. Then we use this construct of

cannot change the value

corresponding uppercase letters.

T

means myptr is a constant pointer an place of const in this statement and write

const int

tatem nt describes that myptr

val u want to pass the ar the values sto declaration (i.e. const int *myptr) in the called function declaration. We write the declaration of the function like

fn ( const int *myptr)

This declaration informs the function that the receiving value is a constant integer. The function cannot change this value. Thus we can use the address of that value for manipulations but stored at that location.

Example 2

Let’s consider an example in which we use the pointers to make a call by reference. We want to convert the lowercase letters of a string (character array), to their

docsity.com

c. In the body of the function, we pass the character to function islower. This function returns true if the character is a lowercase letter and acters in the range ‘a’ through ‘z’ are converted to their letters by function toupper. Function toupper takes one haracter as an argument. If the character is a lowercase letter, the corresponding

we have eader file in our program. We include it in the same way, as we clude .h>.

include

if ( islower ( *sptr) )

++ sptr; // move sptr to the next

We write a function convertToUppercase, which processes the string s one character at a time using pointer arithmeti a false otherwise. The char corresponding uppercase c uppercase letter is returned, otherwise the original character is returned. The functions toupper and islower are part of the character handling library . So to include this h in

include

//declare the functions prototype void convertToUppercase (char *) main () { char s [30] = “Welcome To Virtual University” ; cout << “The string before conversion is: “ << s << endl ; convertToUppercase ( s) ; //function call cout << “The string after conversion is: “ << s ; }

void convertToUppercase (char *sptr) { while ( *sptr != ‘\0’ ) {

*sptr = toupper ( *sptr ); //convert to uppercase

character } }

Following is the output of the program. The string before conversion is : Welcome To Virtual University The string after conversion is : WELCOME TO VIRTUAL UNIVERSITY

E xercise

  1. Modify the above program so that it gets a string from user and converts it into lowercase.

docsity.com