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

Module 3.2 Poionter

The document discusses pointers in C++, highlighting their importance in simulating call-by-reference and manipulating dynamic data structures. It explains the concept of pointers, their declaration, initialization, and usage, including dereferencing and pointer arithmetic. Additionally, it covers related topics such as null pointers, void pointers, and the relationship between arrays and pointers.

Uploaded by

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

Module 3.2 Poionter

The document discusses pointers in C++, highlighting their importance in simulating call-by-reference and manipulating dynamic data structures. It explains the concept of pointers, their declaration, initialization, and usage, including dereferencing and pointer arithmetic. Additionally, it covers related topics such as null pointers, void pointers, and the relationship between arrays and pointers.

Uploaded by

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

INDIAN INSTITUTE OF TECHNOLOGY ROORKEE

EEC-101
Programming with C++
Module-3:
Pointers
About Subject
• Aggregate Data-types:
– Arrays
– Pointers
– Structures
– Dynamic data and Pointers
– Dynamic arrays

2
Pointers

• Pointers is one of the most powerful features of C++


• Pointers enable programs
– to simulate call-by-reference
– create and manipulate dynamic data structures

3
The Reference Operator
• When a variable is declared, three fundamental attributes are associated with it:
– its name,
– its type, and
– its address in memory.

• For example, the declaration int n;


– associates the name n
– the type int
– the address of some location in memory where the value of n is to be stored.

(suppose that address is 0x3fffd14 in hexadecimal notation)

4
• Visualize n like this:
0x3fffd14 0x3fffd14
n n 33
int int
• box represents the variable’s storage location in memory
• variable’s name is on the left of the box
• variable’s type is below the box.
• the variable’s address (0x3fffd14) is above the box
• If the value of the variable is known (n=33), then it is shown inside the box:

5
• The value of a variable is accessed by means of its name, e.g, we can print the value of n
with the statement:
cout << n;

• The address of a variable is accessed by means of the address operator &, e.g, we can
print the address of n with the statement:
cout << &n;

• The address operator & “operates” on the variable’s name to produce its address.

6
Example

7
Reference
• A reference is an alias, a synonym for another variable.
• It is declared by using the reference operator & appended to the reference’s type.

int n = 55;
int& r = n; // r is a reference for n

• Like a constant, a reference must be initialized when it is declared ( A synonym must have
something for which it is an alias. Every reference must have a referent)

8
Example

9
Use Cases
• when used as a prefix to a variable name
– it returns the address of that variable (e.g. int n; cout<<&n;)

• when used as a suffix to a type in a variable declaration-


– it declares the variable to be a synonym for the variable to which it is initialized ( e.g. int n = 55;
int& r = n;)

• when used as a suffix to a type in a function’s parameter declaration


– it declares the parameter to be a reference parameter for the variable that is passed to it . e.g.
swap(int& x, int& y)

• All of these uses are variations on the same theme: the ampersand refers to the address at
which the value is stored.

10
Summary
• Reference is another name (alias) for a variable.

• It is a pointer but a constant one – once declared it cannot be made an alias of another
variable, e.g , int count; int & refCount = count;

• A reference declaration must have initialization and it can be initialized to a variable.

• A variable can have several references (aliases) – all references hold the same address.

• Reference is not a separate variable– it does not occupy space in memory

• Any arithmetic operation on reference is actually an operation on the referred variable

11
Pointers
• The reference operator & returns the memory address of the variable to which it is
applied.

• We can also store the address in another variable.

• The type of the variable that stores an address is called a pointer.

• If the variable has type int, then the pointer variable must have type “pointer to int ,”
denoted by int*

A pointer is a variable and it stores the address of another variable or function.

12
Why Pointer?

Object orientation(OO), or object-oriented


programming (OOP), is a programming
paradigm that organizes software design
around objects, or reusable units of data and
behavior.

13
Pointer
• So if I initialize an integer variable named x to 10,i.e,
int x=10
then x is of type integer and it's bound to some memory location, and it contains the
value 10.

• That means that I can declare a pointer variable that stores the address of x.

• So a pointer is a variable. That means that the pointer has a memory location
where it's bound to.
• It has a type, it has a value, and the value is an address.

14
Pointer Declaration

• we declare pointer variables in exactly the same way except that we add the asterisk prior to the
variable name.
• In this context, the asterisk does not function as a mathematical operator, it serves to declare the
pointer.
• The way you read these declarations is right to left. So the first example int pointer is a pointer to an
integer, double pointer is a pointer to a double.

int *int_ptr; // declares int_ptr to be of type int *// pointer to an integer

int *ptr, n; // declares ptr as pointer to int, n is declared to be an integer

double *ptr1, *ptr2; // pointers to double values


15
Pointer Initialization
• Just like all variables, if we don't initialize our variables, they will contain garbage data. In this case, all the
pointer variables declared, contain garbage data.

• So let's see how we can initialize pointer variables.

• In c++, it's very important that you always initialize all pointer variables before you use them. If you don't
initialize a pointer variable, it will have garbage data. In this case, that garbage data represents an address.

• So you can think of an uninitialized pointer as pointing anywhere.

• So, if we use it, we could be accessing memory that we have no business messing around with.
• We don't even know what that memory is.

16
Null Pointer
Initialize pointers to “point nowhere”.

• In these examples, we're initializing the


pointer variables to zero that's what null
pointer represents this means that we're
initializing the pointers to point
nowhere.

• We can also initialize pointers to actually


point to a variable, and we'll do that
next.

17
• Initializing pointer variables is just like initializing non-pointer variables. We can use an initializer list syntax.
int n {0};

• Let's review what we just talked about since it's very, very important to understand.
– Always initialize all pointer variables.
– Uninitialized pointers contain garbage data and point anywhere.
– Use null pointer to initialize your pointers unless you initialize them to a variable to a function, this nulls out the
pointer.

• One of the most common pointer-related errors that I've seen in code reviews is uninitialized pointers.
• Most of the time this didn't cause a problem, but the potential for trouble is there.

So always initialize your pointers.


18
Storing an Address in a Pointer Variable

• When we declare pointers, they're typed pointers. This means that we explicitly declare the pointer variable to
point to a variable of a specific type.
• In this example, we're declaring an integer score and initializing it to 10 and a double high temp and initializing it
to 100.7.
• Then, we declare the score pointer as a pointer to an integer. We assign the address of score to score pointer.
The compiler is fine with that since the score pointer holds addresses of integers and scores an integer.
• In the case, when we’re assigning the address of high temp to score pointer. The compiler won’t let you do this,
you’ll get a compiler error. The issue is that there’s a type conflict.
19
Example

0x61fde4 0x61fdd8
score 10 sc_ptr 0x61fde4
int int *
20
Accessing Pointer Address

Pointer is a variable.
That means that the pointer has a memory
location where it's bound to.
It has a type.
it has a value, and the value is an address.

21
Size of Pointer Variables
• Don’t Confuse the size of a pointer and the size of what it points to
• All pointers in a program have the same size even though they may be pointing to a very large
or very small type.

22
Example

23
Pointers
• The variable p is called a “pointer” because its value “points” to the location of
another value.
• If the value to which it points is an int, then it is an int pointer .
• The value of a pointer is an address.
• That address depends upon the state of the individual computer on which the program is
running.
• A pointer can be thought of as a “locator”: it tells where to locate another value.

• Often we will need to use the pointer p alone to obtain the value to which it points.

• This is called “dereferencing” the pointer and is accomplished simply by applying the star
* (the asterisk) symbol as an operator to the pointer (*p)
24
Dereferencing a Pointer
• Accessing the data we're pointing to is called dereferencing a pointer.

• If sc_ptr is a pointer and has a valid address, then you can access the data at the address
contained in the sc_ptr using the dereferencing operator *

25
Dereferencing
• The address operator & and the dereference operator * are inverses of each other:
• n = = *p whenever p == &n.

• This can also be expressed as n = = *&n and p == &*p.

Address

Content

Address

&*pointer
26
Example

27
Example

28
Summary
• What Are Pointers?
• A pointer is a variable whose value is the address of another variable.
• Like any variable or constant, you must declare a pointer before you can work with it.
• The general form of a pointer variable declaration is:
• type *var-name;

• Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer
variable.
• The asterisk you used to declare a pointer is the same asterisk that you use for multiplication.
• However, in this statement the asterisk is being used to designate a variable as a pointer.

• Pointers are address variables.


• Contain memory address as their values.
• They provide a path to a value via its address rather than its name – indirection

29
Pointer Arithmetic
• Pointers can be used in
– Assignment expressions
– Arithmetic Expressions
– Comparision Expressions

• Only four arithmetic operators are valid for use with pointers
– Unary operators:
• ++(increment) and
• --(decrement)
– Binary operators:
• +(addition) and
• - (subtraction)

30
Pointer Arithmetic
• a pointer may be incremented (++) or decremented (--)

• an integer may be added to (+, +=) or may be subtracted from (-, -=) the pointer

• an arithmetic operation moves the pointer forward or backwards. The amount of shift
depends on the size of its type

31
Hexadecimal Numbers
• Decimal number-10 unique symbols • Hexadecimal number-16 unique symbols
(0,1,2,3,4,5,6,7,8,9) (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F)

32
33
Hexadecimal Addition
• Basically, hexadecimal addition is similar to decimal addition. But in hexadecimal addition,
a carry is generated to the next higher column if the sum is greater than or equal to 16.

Example-1 Example-2
Add (5A)16 and (BF)16. Add (ABC)16 and (2A9)16.

1
5 A
+ B F
1 1 9

34
++ and --
• (++) operator increments a pointer to point to the next element.
• For example, the initial memory location of p is 7004 and if the elements that it stores
are of two bytes then p++ points next location as 7006

• Similarly (--) decrements the pointer to point to the previous element


• if element is of int type( 4 bytes) and initial position is 9004 then, p-- points 9000,

• Also, p=p+2 points to 9012.

35
+ and -

if element is of int type( 4 bytes) and initial position is 9004 then,


int_ptr=int_ptr+3 will move int_ptr to 9004+4*3=9016

36
Size of Data Types

37
Example

38
Subtracting two pointers

39
Comparing two Pointers

40
Comparing the Data Pointers Point to

41
Array and Pointers
• In C++, we can manipulate arrays by using pointers to them. These kinds of pointers that point to the arrays
are called array pointers or pointers to arrays.
• a pointer can be made to point to the first element of an array as:

int n[5], *nptr;


nptr = n;
// or nptr = &n[0];

• nptr can be made to point to any element, for example nptr = &n[2];
• nptr++ will move the pointer one element forward in the array from its current position
• nptr += 2; will make nptr move forward by two elements, i.e., by 8 bytes
• a pointer may be subtracted from another – the operation gives the element-gap between them
• pointers can be compared using equality and relational operators
• pointer arithmetic is applied mostly on arrays because the elements of an array are stored in contiguous
memory

42
int *ptr = a;
*(ptr+2)
*(ptr+4)
*ptr

a[0] a[1] a[2] a[3] a[4]


int a[5];

43
Example

44
• Array name is a constant pointer to its first element

45
Result

46
Pointers and Arrays
int num[5]; // declare array of 5 integers

• num is actually a pointer that points to the first element of the array
• Since, the array variable is a pointer, we can dereference it, which returns array element 0
int num[5] = { 20, 15, 45, 85, 10 };
// dereferencing an array returns the first element (element 0)
cout << *num; // will displays 20

char ctyName[ ] = “Roorkee”; // C-style string (also an array)


cout << *ctyName; // will display ‘R'

47
Example

48
49
Example
• WAP to find sum of array Elements using Pointer

50
Void Pointer
• NULL and Void pointers are not same.

• A null pointer is a value that any pointer may take to represent that it is pointing to
“nowhere”.

• A void pointer is a special type of pointer that can point to somewhere without a specific
type.

• NULL pointer refers to the value stored in the pointer itself.

• Void pointer refers to the type of data it points to.

51
Example: Null Pointer

52
Void Pointer

• In C++, a void pointer is a pointer that is declared using the ‘void‘ keyword (void*).
• It is different from regular pointers it is used to point to data of no specified data type.
• It can point to any type of data so it is also called a “Generic Pointer“.

• Void Pointer cannot be dereferenced.


• It must be type-casted before dereferencing.
• Arithmetic operations are not allowed on Void Pointers.

53
Example

54
Example: pointer type-casting

55
Constant Pointers
• In constant pointers, the pointer points to a fixed memory location, and the value at that
location can be changed because it is a variable, but the pointer will always point to the
same location because it is made constant here.

• A constant pointer is declared as : int *const ptr (the location of 'const’ makes the pointer
'ptr' as constant pointer)

56
Example

57
Pointer to Constant
• These pointers cannot change the value they are pointing to.
• In other words, they cannot change the value of the variable whose address they
are holding.

• Syntax: const int* ptr

• In the pointers to constant, the data pointed by the pointer is constant and cannot
be changed. Although, the pointer itself can change and point somewhere else (as
the pointer itself is a variable).

58
Example

59
Constant Pointer to Constants
• In the constant pointers to constants, the data pointed to by the pointer is constant
and cannot be changed.
• The pointer itself is constant and cannot change and point somewhere else.

60
Example

61
Array of Pointers or Pointer array
• A pointer array is a homogeneous collection of indexed pointer variables that are
references to a memory location.
• It is generally used when we want to point at multiple memory locations of a similar data
type.
• We can access the data by dereferencing the pointer pointing to it.

62
Array of Pointers
• An array of pointers is an array (stored in contiguous memory locations) of pointer variables. These are also
known as pointer arrays.
• The declara on of an array of pointers to an integer −> int *ptr[5];
• This declares ptr as an array of 5 integer pointers. Thus, each element in ptr, now holds a pointer to an int
value.

Example: Integer Array

// array of integers

63
Example: Array of Pointers

Array of
Pointers

64
C++ Strings
• A string is a null-terminated array of characters.
– null terminated means there is a character at the end of the array that has the value 0
(null).
• Pointers are often used with strings, for example,
char *see = “IIT”;

see

‘I' ‘I' ‘T' 0

65
Array of Pointers
• An array of pointers could be used to create an array of strings (string array ).
• In C++, a string is actually a pointer to its first character; thus, a string array would be
essentially an array of pointers to the first character of a string in each array's element.

Example: Char Array without pointer

66
Example
Example: Char Array without pointer

• Both the number of strings and the size of the strings are fixed.
• The first dimension (4 in this case), may be left out, and the appropriate size will be
computed by the compiler.
• The second dimension, however, must be given (in this case, 15), so that the compiler
can choose an appropriate memory layout
• Each string can be modified but will take up the full space given by the second
dimension.
• Each will be laid out next to the other in memory and can’t change size.
67
Example

68
Strings Example
• WAP to Count the Number of chars in a string

Method-1 Method-2

int Count( char *s) //while int count_string( char *s)


the thing pointed to by s is not null {
{ char *ptr = s;
int n=0; while (*ptr) {
while (*s) { ptr++;
n++; //increment count }
s++; //set s to point to the next char return(ptr - s);
} }
return(n);
}

69
Example

70
2-D Array Using Pointer

71
Pointers and Functions
• Ways to pass arguments to a function
– by value
– by reference
– by pointer

• If the function is indented to modify the variables in the calling program:


– passed by value cannot be used, since the function obtains only the copy of the
variable
– either a reference argument or a pointer can be used

72
Passing Pointer to a Function

73
Example
WAP to double a number using pass by
reference and also by pointer

74
• When main() function calls the function it
supplies the address of the variables as the
argument:
Multby2 (&x, &y);
• These are not the variables that are being
passed by reference . They are variables’
address.

75
• Since the multby2( ) function is passed
an address, it must use the indirection
operator *ptrc, *ptrd to access the value
stored at that address.

• For example:
*ptrx *=2; // ( same as *ptrx = *ptrx *2)

76
• ptrc and ptrd contains addresses of x and y
respectively
• anything done to *ptrc is actually done to x
• anything done to *ptrd is actually done to y

• Passing a parameter to a function in this case is


in some ways similar to passing by reference.
• Both permit the variable in the calling program
to be modified by the function

• A reference is an alias for the original value,


while a pointer is an address of the variable.

77
Example

78
Returning a Pointer from a Function

79
Example

80
Never Return a Pointer to a Local variable
This will compile just fine since the address of size is the address of an
integer and that's what the function returns.

But what's the problem?


• We're returning the address of a local variable in the function.
• The variable's on the stack and the function just terminated, so
this variable is now past its lifetime.
• The next time the function is called, or any function is called,
the stack area will be reused, and the pointer will now be
pointing into that new function’s activation record.

• If you overwrite the data it's pointing to, you could trash the
• stack pointers, static links, all kinds of important information on
the activation record.

81
Passing arrays in pointer notation

82
• * ptrArr++ increments the pointer and not the pointer content
• Complier interprets it as *(ptrArr++),i.e., pointer increments first and then indirection or dereference
• *ptrArr++ *=2; // means “
– increment ptrArr to go to the next element,
– then dereference its old value (since postfix ++)
– Similar to writing the following two statements *ptrArr=2*(*ptrArr); ptrArr++ ;

83
Address of a Function
• Address of Function: We all know that every function’s code resides in memory, so
every function has an address like all other variables in the program.
• The name of a function can be used to find the address of the function.
• We can get the address of a function by just writing the function’s name without
parentheses.

– The function pointer is used to point functions, similarly, the pointers are used to point
variables.
– It is utilized to save a function’s address.
– The function pointer is either used to call the function or it can be sent as an argument
to another function.

84
85
Pointer to Functions/Function Pointers
• Like array name, functions name is actually a constant pointer

• Visualize value of the pointer as the address of the code that implements the function
• A pointer to a function is a pointer whose value is the address of the name
• A pointer to a function is a pointer to a constant pointer

Let us understand this way:

int func(int); // declares function func

int (*pf)(int x);// declares function pointer pf


pf = &func; OR pf =func; //name function gives its address

86
Declaration
• Their declaration is easy: write the declaration as it would be for the function, say
int func (int a, float b);

and simply put brackets around the name and * in front of it: that declares the pointer.
int (*func)(int a, float b);

• Because of precedence, if you don't parenthesize the name, you declare a function
returning a pointer:

// function returning pointer to int


int *func(int a, float b);

//pointer to function returning int


int (*func)(int a, float b);
87
Calling the Function
• You can call the function using one of two forms:

– Using Pointer : (*func)(1,2);

– Using function name: func (1,2);

88
Example

89
Passing a function pointer as a parameter
• A function pointer stores the memory address of the function.

• When we want to pass the return value to the next function.

• We have two methods to perform this task.

– First, either pass the value we got


– Second, pass the function pointer that already exists.

90
Example

91
92
Example-2

93
Array of Function-Pointers

94
Thanks

95

You might also like