0% found this document useful (0 votes)
18 views49 pages

13 Pointers

Uploaded by

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

13 Pointers

Uploaded by

amemaqueenie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Pointers

Introduction to Pointers
• When we declare a variable, some memory is
allocated for it.

• Thus, we have two properties for any variable:


1. Its Address
2. and its Data value
Memory Address Value

E.g., char ch = ‘A’;


ch
311 65
Introduction to Pointers
• How to get the memory-address of a variable?

• Address of a variable can be accessed through the


referencing operator “&”
– Example: &i  will return memory location
where the data value for “i” is stored.

• A pointer variable is one that stores an address.


Introduction to Pointers
• We can declare pointers as follows:

Type* <variable Name>;

– Example:
int* P;

- creates a pointer variable named “P”, that will


store address (memory location) of some int
type variable.
Introduction to Pointers
• Question:

Why is it important to declare the type of the variable


that a pointer points to?

Aren’t all addresses of the same length?


Introduction to Pointers
• Answer:
- All memory addresses are of the same length,
– However, when we perform an operation of the
type “p++” where “p” is a pointer variable  for
this operation to make sense the compiler needs to
know the data type of the variable “p” points to.
– Examples:
– If “p” is a character-pointer then “p++” will
increment “p” by one byte
– if “p” is an integer-pointer its value on “p++”
would be incremented by 4 bytes
Introduction to Pointers
• Summary:
– Pointer is a data-type that stores addresses, it is declared
as follows: int* a; char* p; etc.

– The value stored in a pointer p can be accessed through


the dereferencing operator *

– The address of a memory location of a variable can be


accessed through the reference operator “&”.

– Pointer Arithmetic: Only Addition and Subtraction are


allowed.
The address of Operator - &
• The & operator can be used to determine the
address of a variable, which can be assigned to a
pointer variable
– Example:
int* p1;
int v1=99;
p1 = &v1;

Now p1 points to the memory location, where v1 is


stored.
- v1 is an integer variable
- P1 is a integer pointer
The Dereferencing Operator - *
• C++ uses the * operator in yet another way with
pointers
– "The variable values pointed by p"  *p
– Here the * is the dereferencing operator
• p is said to be dereferenced

int v1=99;
int* p= &v1;
cout<<“ P points to the value: “<<*p;
A Pointer Example
int v1 = 0;
v1 and *p1 now refer to
int* p1 = &v1; the same variable
*p1 = 42;
cout << v1 << endl;
cout << *p1 << endl;

Output:
42
42
Pointer Assignment
• Assignment operator ( = ) is used to assign value
of one pointer to another

• Pointer stores addresses so p1=p2 copies an


address value into another pointer
int v1 = 55; Output:
int* p1 = &v1;
int* p2; 55
p2=p1; 55
cout << *p1 << endl;
cout << *p2 << endl;
Caution! Pointer Assignments
• Some care is required making assignments to
pointer variables:

– p1= p2; // changes the location that p1 "points" to

– *p1 = *p2; // changes the value at location that


// p1 "points" to
Another Pointer Example
int i = 1;
int j = 2;
int* ptr;
ptr = &i; // ptr points to location of i
*ptr = 3; // contents of i are updated
ptr = &j; // ptr points to location of j
*ptr = 4; // contents of j are updated
cout << i << " " << j << endl;

Output:
3
4
Null Address
• Like a local variable, a pointer is assigned an
arbitrary address if you don’t initialize it.
• 0 is a pointer constant that represents the empty or
Null address
– Its value indicates that pointer is not pointing to a valid
object
– Cannot dereference a pointer whose value is Null
int *ptr = 0; OR int *ptr=NULL;
cout << *ptr << endl; // ERROR: ptr
// does not point to
// a valid int
Relationship between Arrays and Pointers
• Arrays and pointers are closely related:

void main()
{
int numbers[]={10,20,30,40,50};
cout<<numbers[0]<<endl; 10
cout<<numbers<<endl; Address e.g., &34234

cout<<*numbers<<endl; 10
cout<<*(numbers+1); 20
}
Arrays and Pointers
• Arrays and pointers are closely related:
– Array name is the starting address of the array

• Let int A[25];


int *p; int i, j;

• Let p = A;

• Then p points to A[0]


p + i points to A[i]
&A[j] == p+j
Class Exercise – Printing Array values using Pointers
Class Exercise – Printing Array values using Pointers
• Write a C++ program that creates an array of 10
elements. The program should take input in the array
from the user. Then the program calculates average of
the values in the array.
Please note: array elements should be accessed using
pointer notation only.
Class Exercise – Printing Array values using Pointers
Swapping variables using Pointers
void main() {
char a = ‘A';
char b = ‘Z';
char *Ptr1= &a;
char *Ptr2= &b;

char temp = *Ptr1;


*Ptr1 = *Ptr2;
*Ptr2 = temp;

cout << a << b << endl;


}
Swapping variables using Pointers
Void Pointer
• void* is a pointer to no type at all:
• Any pointer type may be assigned to void *

int iVar=5;
float fVar=4.3;
char cVar=‘Z’;
int* p1;
void* vp2;
p1 = &iVar; // Allowed
p1 = &fvar; // Not Allowed
P1 = &cVar; // Not Allowed
vp2 = &fvar; // Allowed
vp2 = &cVar; // Allowed
vp2 = &iVar; // Allowed
Strings As Pointers
• Another way of accessing a
contiguous chunk of memory, instead
of with an array, is with a pointer:
• Since we are talking about strings, which are
made up of characters, we'll be using
pointers to characters, or rather, char *s.
• However, pointers only hold an
address, they cannot hold all
the characters in a character
array.
Strings As Pointers
• This means that when we use a char *
to keep track of a string, the
character array containing the
string must already exist (having
been either statically- or
dynamically-allocated).

• Below is how you might use a character pointer to keep


track of a string.
Strings As Pointers
char label[] = "Single";
char label2[10] = "Married";
char *labelPtr;
labelPtr = label;
• We would have something like the following in memory (e.g., supposing that the array label started
at memory address 2000, etc.):

label @2000
------------------------------
| S | i | n | g | l | e | \0 |
------------------------------

label2 @3000
------------------------------------------
| M | a | r | r | i | e | d | \0 | | |
------------------------------------------

labelPtr @4000
--------
| 2000 |
--------
Strings As Pointers
Note: Since we assigned the pointer the address of
an array of characters, the pointer must be a
character pointer--the types must match.

Also, to assign the address of an array to a pointer,


we do not use the address-of (&) operator since the
name of an array (like label) behaves like the
address of that array in this context.
Strings As Pointers
Now, we can use labelPtr just like the array name label. So, we could access the third character in the string with:

cout << "Third char is: " << labelPtr[2] << endl;

It's important to remember that the only reason the pointer labelPtr allows us to access the label array is because we made
labelPtr point to it. Suppose, we do the following:
labelPtr = label2;

Now, no longer does the pointer labelPtr refer to label, but now to label2 as follows:

label2 @3000
------------------------------------------
| M | a | r | r | i | e | d | \0 | | |
------------------------------------------

labelPtr @4000
--------
| 3000 |
--------

So, now when we subscript using labelPtr, we are referring to characters in label2. The following:

cout << "Third char is: " << labelPtr[2] << endl;

prints out r, the third character in the label2 array.


Dynamically Allocated Strings
Since sometimes you do not know how big a string
is until run-time, you may have to resort to dynamic
allocation.

The following is an example of dynamically-


allocating space for a string at run-time:
Dynamically Allocated Strings
void SomeFunc(int length)
{
char *str;

// Don't forget extra char for nul character.


str = new char[length + 1];

...

// Done with str.


delete [] str;
...
Dynamically Allocated Strings
Basically, we've just asked new (the allocation operator)
to give us back enough space for an array of the desired
size. Operator new requires the type of elements (here,
char) and the number of elements needed (given as the
array size between [ and ]).

Note that unlike static allocation, e.g.:

char name[20];

the size can be variable (when using new for allocation).


Dynamically Allocated Strings
We keep track of the dynamically-allocated array
with a pointer (e.g., the return value of the call to
new is stored in str).

We then can use that pointer as we used pointers to


statically-allocated arrays above (i.e., we access
individual characters with str[i], pass the string to a
function, etc.).

Finally, note that when we are done using the string,


we must deallocate it.
Dynamically Allocated Strings
Note: Note the use of [] when using delete to
deallocate an array.

Here, we deallocate the string in the same function,


but in some cases we might still need it after
SomeFunc() ends, so we'd deallocate it later.
Constant Pointer
• A constant pointer is a pointer such that we cannot
change the location (address) to which the pointer
points to:

char c = 'c';
char d = 'd';
char* const ptr1 = &c;
ptr1 = &d; // Not Allowed

int* const ptrcInt; //ptr is constant pointer to int


Pointer to Constant
• A pointer through which we cannot change the value
of variable it points is known as a pointer to constant.
• These type of pointers can change the address they
point to but cannot change the value kept at those
address.

int var1 = 0;
const int* ptr = &var1;
*ptr = 1; // Not Allowed
cout<<*ptr;
Pointer to String Constant
char*  <string Literal>
Pointer to String Constant
Pointer to String Constant
Pointer to String Constant - Example
// Copying string using Pointers

char* str1 = “Self-conquest is the greatest victory.”;


char str2[80]; //empty string
char* src = str1;
char* dest = str2;

while( *src ) //until null character,


*dest++ = *src++; //copy chars from src to dest

*dest = ‘\0’; //terminate dest

cout << str2 << endl; //display str2


Pointer to String Constant - Example
Comparing Pointers
• If one address comes before another address in
memory, the first address is considered less than
the second address.

• Two pointer variables can be compared using C++


relational operators: <, >, <=, >=, ==

• In an array, elements are stored in consecutive


memory locations, E.g., address of Arr[2] will be
smaller than the address of Arr[3] etc.
Functions Pass by using Reference Pointers
c

• Pass-by-reference with pointer arguments


• Use pointers as formal parameters and
addresses as actual parameters

• Pass address of argument using & operator


– Arrays not passed with & because array name
already an address
– Pointers variable are used inside function
Pass by Reference Pointers– Example1
c

void func(int *num)


{
cout<<"num = "<<*num<<endl;
*num = 10;
cout<<"num = "<<*num<<endl;
}

void main()
{
int n = 5;
cout<<"Before call: n = "<<n<<endl;
func(&n);
cout<<"After call: n = "<<n<<endl;
}
Pass by Reference Pointers– Example1
c
Pass by Reference Pointers– Example2
c
void compDouble(int* Ar)
{
for(int i=0;i<10;i++)
{ *Ar=(*Ar)*2;
Ar++;
}
}
void main()
{ int Arr[10]={0,1,2,3,4,5,6,7,8,9};
compDouble(Arr);
for(int i=0;i<10;i++)
cout<<Arr[i]<<endl;
}
Pass by Reference Pointers– Example2
c
Class Exercises
• Find errors:
int ptr*;

int x, *ptr;
&x = ptr;

int x, *ptr;
*ptr = &x;

int x, *ptr;
ptr = &x;
ptr = 100; //Store 100 in x
cout<<x;
Class Exercises <continued…>
int numbers[]={10,20,30,40,50};
cout<<“Third element of the array is: “;
cout<<*(number+3);

int values[20], *ptr;


ptr = values;
ptr *= 2;

float level;
int *float_ptr = &level;

int *iptr = &ivalue;


int ivalue;
Class Exercise 2 – Bubble sort using pointer notation
• Write a C++ program that creates an array of 10
elements. The program should then take input in the
array from the user. After that, the program sorts the
array elements in descending order. The sorting code
should access array elements using pointer notation.
Class Exercise 2 – Bubble sort using pointer notation

You might also like