0% found this document useful (0 votes)
8 views63 pages

Pointers

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)
8 views63 pages

Pointers

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/ 63

Pointers

ITP 2024
Pointers
• What?
• Why?
• How?

10/9/24 IIT Kandi 2


What are Pointers?
• Pointers are variables that contain the
address of another variable
• Normal variables contain a specific value (direct
reference)
• The pointer points to that variable
• Referencing a value through a pointer is
called indirection (indirect reference).
• A variable name directly references a
value, and a pointer indirectly
references a value

IIT Hyderabad
10/9/24 3
Why Pointers?
Memory efficiency: Pointers can handle large data efficiently. Passing large structures or arrays
by pointer instead of value prevents the overhead of copying entire blocks of memory (allows
pass-by-reference).
Memory management: Pointers are crucial for dynamically allocating memory at runtime.
Useful for creating dynamic data structures.

Manipulating Arrays and Strings: Pointers can be used to access array elements directly.
Pointer arithmetic allows you to traverse arrays efficiently.

Function Pointers: Pointers can be used to point to functions, allowing functions to be passed
as arguments, stored in arrays, or dynamically assigned at runtime.

10/9/24 IIT Hyderabad 4


How to use Pointers?
• Needs to be declared before use. Read as: countPtr is a pointer to an integer.
• Int *countPtr;

• The * is associated with the variable. The * doesn’t distribute to each var.
• int *a, b; // a is a pointer variable, b is a regular variable
• Int *c, *d; // Both c and d are pointers

• Pointers can be initialized to NULL, 0, or any memory address


• A pointer with NULL value does not point to anything
• NULL is a symbolic constant with value 0 and is defined in <stddef.h>
• Initializing a pointer to 0 is equivalent to initializing it to NULL.
• The constant NULL is preferred because it emphasizes that you’re initializing a
pointer rather than a variable that stores a number
10/9/24 IIT Hyderabad 5
Pointer Operators: Address(&)
• Address operator (&) gives address of variables
• int y = 5;
• int *yPtr = &y;
• yPtr “points to” y

10/9/24 IIT Hyderabad 6


Good Practices when using Pointers
.Include the letters ptr in pointer variable names to make it clear that
these variables are pointers and thus need to be handled appropriately.
• Initialize pointers to prevent unexpected results.

10/9/24 IIT Hyderabad 7


Pointer Operators: Indirection(*)
• Indirection operator or dereferencing operator (*) gives the content of
the memory location (value of the variable to which pointer points to)
• int x = 10;
• int *xPtr = &x;
• int y = *xPtr;
• x = 12;
• %p format specifier can be used in printf statements to print memory
addresses/ pointer values
• * and & are inverses
• They cancel each other out

10/9/24 IIT Hyderabad 8


Common Programming Error
• Dereferencing a pointer that has not been properly initialized or that
has not been assigned to point to a specific location in memory is an
error. This could cause a fatal execution-time error, or it could
accidentally modify important data and allow the program to run to
completion with incorrect results.

10/9/24 IIT Hyderabad 9


A Sample Program using Pointers

If aPtr points to a, then &a and


aPtr have the same value.
a and *aPtr have the same value
&*aPtr and *&aPtr have the same value

10/9/24 IIT Hyderabad 10


Enabling Calling Functions by Reference
• Arguments are passed to a function in two ways:
1. pass-by-value or
2. pass-by-reference
• Generally, arguments are passed by value
• To accomplish Pass-by-reference, address of a variable is passed as
argument using & operator
• Arrays are passed by reference. Arrays are not passed with & because
the array name is already a pointer

10/9/24 IIT Hyderabad 11


Enabling Calling Functions by Reference
• A function that receives the address of a variable in the caller can use the
indirection operator (*) to modify the value at that location in the caller’s
memory, thus effecting pass-by-reference
• All changes made to the memory location are seen in the in the caller
• No need to return those values by the called function
• It enables a function to “return” multiple values by modifying caller’s variable
• * operator
• Used as alias/nickname for variable inside of function
• void double( int *number )
• {
• *number = 2 + ( *number );
• }
• *number used as nickname for the variable passed

10/9/24 IIT Hyderabad 12


Pass-by-Reference with a Pointer Argument

Function prototype takes a pointer argument

Function cubeByReference is
passed an address, which can be the
value of a pointer variable

In this program, *nPtr is number, so this


statement modifies the value of number
itself.

10/9/24 IIT Hyderabad 13


Pointer Parameters in Function Prototypes
• Pointer parameters are mentioned as pointer variables in function
prototype/signature
• void increment(int *arg)
• void newRandNum (int *num)
• The compiler does not differentiate between a function that receives
a pointer and one that receives a one-dimensional array
• If the function parameter is int b[], the compiler converts the
parameter to the pointer notation int *b.
• Similarly, if the parameter is const int b[], the compiler converts the
parameter to const int *b
10/9/24 IIT Hyderabad 14
Call-by-value
Analysis (part-1)

IIT Hyderabad 10/9/24 15


Call-by-value
Analysis (part-2)

IIT Hyderabad 10/9/24 16


Call-by-reference
with a pointer arg
Analysis

IIT Hyderabad 10/9/24 17


Using call-by-reference: Guidelines
Use call-by-value to pass arguments to a function unless the caller
explicitly requires the called function to modify the value of the
argument variable in the caller’s environment. This prevents accidental
modification of the caller’s arguments and is another example of the
principle of least privilege.

10/9/24 IIT Hyderabad 18


Using the const Qualifier with Pointers
• Recall: const qualifier
• Variable cannot be changed
• Use const if function does not need to change a variable (to prevent unintentional side effects)
• Attempting to change a const variable produces an error
• const pointers
• Point to a constant memory location
• Must be initialized when defined
• int *const myPtr = &x;
• Type int *const – constant pointer to an int
• const int *myPtr = &x;
• Regular (modifiable) pointer to a const int
• const int *const Ptr = &x;
• const pointer to a const int

10/9/24 IIT Hyderabad 19


const Qualifier: Software Engineering Observation
• The const qualifier can be used to enforce the principle of least
privilege. Using the principle of least privilege to properly design
software reduces debugging time and improper side effects, making a
program easier to modify and maintain.

• Only one value can be altered in a calling function when call-by-value is


used. That value must be assigned from the return value of the function.
To modify multiple values in a calling function, call-by-reference must be
used.

10/9/24 IIT Hyderabad 20


Non-constant Pointer to a Non-constant Data

Both sPtr and *sPtr are modifiable

Both sPtr and *sPtr are modified


by the convertToUppercase
function

10/9/24 Sample Footer Text 21


Non-constant Pointer to a Constant Data

Pointer variable sPtr is modifiable, but the


data to which it points, *sPtr, is not

sPtr is modified by function printCharacters

10/9/24 Sample Footer Text 22


Non-constant inter to a Constant Data: Error

Pointer variable xPtr is modifiable, but the


data to which it points, *xPtr, is not

*xPtr has the const qualifier, so attempting


to modify its value causes an error

10/9/24 Sample Footer Text 23


Constant Pointer to a Non-Constant Data

Pointer ptr is not modifiable, but the data to


which it points, *ptr, can be changed

10/9/24 Sample Footer Text 24


Constant Pointer to a Constant Data: Error

Neither pointer sPtr nor the data to which it


points, *sPtr, is modifiable

10/9/24 Sample Footer Text 25


Bubble Sort Using Call-by-Reference
• Implement bubble sort using pointers
• Swap two elements
• swap function must receive address (using &) of array elements
• Array elements have call-by-value default
• Using pointers and the * operator, swap can switch array elements
• Psuedocode
Initialize array
print data in original order
Call function bubble sort
print sorted array
Define bubble sort

10/9/24 IIT Hyderabad 26


Bubble Sort Using Call-by-Reference

10/9/24 IIT Hyderabad 27


Bubble Sort Using Call-by-Reference

10/9/24 IIT Kandi 28


Software Engineering Observation
• When passing an array to a function, also pass the size of the array.
This helps make the function reusable in many programs.

• Global variables usually violate the principle of least privilege and can
lead to poor software engineering. Global variables should be used
only to represent truly shared resources, such as the time of day.

10/9/24 Sample Footer Text 29


Bubble Sort Using Call-by-Reference

Function swap changes the values of the


ints that the two pointers point to

10/9/24 IIT Kandi 30


sizeof Operator
• sizeof
• Returns size of operand in bytes
• For arrays: size of one element * number of elements
• if sizeof( int ) equals 4 bytes, then
• int myArray[ 10 ];
• printf( "%d", sizeof( myArray ) );
• will print 40 – array’s total number of bytes
• sizeof can be used with
• Variable names
• Type name
• Constant values

10/9/24 Sample Footer Text 31


sizeof Operator: Example

floats take up 4 bytes in memory, so 20 floats


take up 80 bytes

10/9/24 Sample Footer Text 32


sizeof Operator: One More Example

10/9/24 Sample Footer Text 33


sizeof Operator: One More Example (Contd.)

10/9/24 Sample Footer Text 34


sizeof Operator: Performance and Portability
• sizeof is a compile-time operator, so it does not incur any execution-time
overhead.
• The number of bytes used to store a particular data type may vary between
systems. When writing programs that depend on data type sizes and that will run
on several computer systems, use sizeof to determine the number of bytes
used to store the data types.

10/9/24 Sample Footer Text 35


Pointer Expressions and Pointer Arithmetic
• Arithmetic operations can be performed on pointers
• Increment/decrement pointer (++ or --)
• Add an integer to a pointer( + or += , - or -=)
• Pointers may be subtracted from each other
• Operations meaningless unless performed on an array

10/9/24 Sample Footer Text 36


Pointer Expressions and
Pointer Arithmetic • 5 element int array on machine with 4 byte ints
• vPtr points to first element v[ 0 ]
• at location 3000 (vPtr = 3000)
• vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] (incremented by 2), but
the machine has 4 byte ints, so it points to
address 3008

10/9/24 Sample Footer Text 37


Pointer Expressions and Pointer Arithmetic:
Portability
• Most computers today have 2-byte or 4-byte integers. Some of the
newer machines use 8-byte integers. Because the results of pointer
arithmetic depend on the size of the objects a pointer points to,
pointer arithmetic is machine dependent.

10/9/24 Sample Footer Text 38


Pointer Expressions and Pointer Arithmetic:
Errors
• Using pointer arithmetic on a pointer that does not refer to an
element in an array.

• Subtracting or comparing two pointers that do not refer to elements


in the same array.

• Running off either end of an array when using pointer arithmetic.

10/9/24 Sample Footer Text 39


Pointer Expressions and Pointer Arithmetic
• Pointers of the same type can be assigned to each other
• If not the same
• +type, a cast operator must be used
• Exception: pointer to void (type void *)
• Generic pointer, represents any type
• No casting needed to convert a pointer to void pointer
• void pointers cannot be dereferenced

• Assigning a pointer of one type to a pointer of another type if neither is


of type void * is a syntax error.
• Dereferencing a void * pointer is a syntax error.

10/9/24 Sample Footer Text 40


Pointers and Arrays: Relationship
• Arrays and pointers closely related
• Array name as a constant pointer to the array’s first element
• Pointers can do array subscripting operations
• Define an array b[ 5 ] and a pointer bPtr
• To set them equal to one another use:
• bPtr = b;
• The array name (b) is actually the address of first element of the array b[ 5 ]
• bPtr = &b[ 0 ]
• Explicitly assigns bPtr to address of first element of b

10/9/24 Sample Footer Text 41


Pointers and Arrays:Pointer/Offset Notation
• Element b[ 3 ]
• Can be accessed by *( bPtr + 3 )
• Where 3 is called the offset. Called pointer/offset notation
• Can be accessed by performing pointer arithmetic on the array itself
• *( b + 3 )

10/9/24 Sample Footer Text 42


Pointers and Arrays: Pointer/Subscript Notation
• Element b[ 3 ]
• Can be accessed by bptr[ 3 ]
• Called pointer/subscript notation
• bPtr[ 3 ] same as b[ 3 ]

• Attempting to modify an array name with pointer arithmetic is a syntax error.


• b += 3

10/9/24 Sample Footer Text 43


Pointers and
Arrays:
Example-1

Array subscript notation

Pointer/offset notation

Sample Footer Text 10/9/24 44


Pointers and
Arrays: Pointer subscript notation

Example-1

Pointer offset notation

Sample Footer Text 10/9/24 45


Pointers and
Arrays:
Example-1

Sample Footer Text 10/9/24 46


Pointers and
Arrays:
Example-2

Sample Footer Text 10/9/24 47


Pointers and
Arrays:
Example-2

Condition of for loop


actually performs an action

Sample Footer Text 10/9/24 48


Arrays of Pointers
• Arrays can contain pointers
• For example: an array of strings
char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };
• Strings are pointers to the first character
• char * – each element of suit is a pointer to a char
• The strings are not actually stored in the array suit, only pointers to the
strings are stored

10/9/24 Sample Footer Text 49


Arrays of Pointers: Another Example: Graphical
Representation

10/9/24 Sample Footer Text 50


Arrays of Pointers: Graphical Representation

10/9/24 Sample Footer Text 51


Pointers to Functions (Function Pointers)
• Pointer to function
• Contains address of function
• Similar to how array name is address of first element
• Function name is starting address of code that defines function
• Function pointers can be
• Passed to functions
• Stored in arrays
• Assigned to other function pointers

10/9/24 Sample Footer Text 52


Function
Pointers:
Example-1

Sample Footer Text 10/9/24 53


Function
30 /* sort array in ascending order; pass function ascending as an
31 argument to specify ascending sorting order */
32
Pointers:
if ( order == 1 ) {
33 bubble( a, SIZE, ascending );
34
Example-1
printf( "\nData items in ascending order\n" );
35 } /* end if */
36 else { /* pass function descending */
37 bubble( a, SIZE, descending );
38 printf( "\nData items in descending order\n" );
39 } /* end else */
40 depending on the user’s choice, the
41 /* output sorted array */ bubble function uses either the
42 for ( counter = 0; counter < SIZE; counter++ ) { ascending or descending
43 printf( "%5d", a[ counter ] ); function to sort the array
44 } /* end for */
45
46 printf( "\n" );
47
48 return 0; /* indicates successful termination */
49
50 } /* end main */
51

Sample Footer Text 10/9/24 54


52 /* multipurpose bubble sort; parameter compare is a pointer to

Function 53 the comparison function that determines sorting order */


54 void bubble( int work[], const int size, int (*compare)( int a, int b ) )

Pointers:
55 {
56 int pass; /* pass counter */
57

Example-1
int count; /* comparison counter */
58
59 void swap( int *element1Ptr, int *element2ptr ); /* prototype */
60
61 /* loop to control passes */
62 for ( pass = 1; pass < size; pass++ ) {
63
64 /* loop to control number of comparisons per pass */
65 for ( count = 0; count < size - 1; count++ ) {
66
67 /* if adjacent elements are out of order, swap them */
68 if ( (*compare)( work[ count ], work[ count + 1 ] ) ) {
69 swap( &work[ count ], &work[ count + 1 ] );
70 } /* end if */
71
Note that what the program
72 } /* end for */
73 considers “out of order” is
74 } /* end for */ dependent on the function
75 pointer that was passed to the
76 } /* end function bubble */
bubble function
77

Sample Footer Text 10/9/24 55


78 /* swap values at memory locations to which element1Ptr and

Function 79 element2Ptr point */


80 void swap( int *element1Ptr, int *element2Ptr )

Pointers:
81 {
82 int hold; /* temporary holding variable */

Example-1
83
84 hold = *element1Ptr;
85 *element1Ptr = *element2Ptr;
86 *element2Ptr = hold;
87 } /* end function swap */
88
89 /* determine whether elements are out of order for an ascending
90 order sort */
91 int ascending( int a, int b ) Passing the bubble function ascending
92 { will point the program here
93 return b < a; /* swap if b is less than a */
94
95 } /* end function ascending */
96
97 /* determine whether elements are out of order for a descending
98 order sort */
99 int descending( int a, int b )
Passing the bubble function descending
100 {
101 return b > a; /* swap if b is greater than a will
*/ point the program here
102
103 } /* end function descending */

Sample Footer Text 10/9/24 56


Function Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 1

Pointers: Data items in original order

Example-1 2 6 4 8 10 12
Data items in ascending order
89 68 45 37

2 4 6 8 10 12 37 45 68 89

Enter 1 to sort in ascending order,


Enter 2 to sort in descending order: 2

Data items in original order


2 6 4 8 10 12 89 68 45 37
Data items in descending order
89 68 45 37 12 10 8 6 4 2

Sample Footer Text 10/9/24 57


1
Function
/* Fig. 7.28: fig07_28.c
2 Demonstrating an array of pointers to functions */
3 #include <stdio.h>

Pointers: 4
5 /* prototypes */

Example-2 6
7
void function1( int a );
void function2( int b );
8 void function3( int c );
9
10 int main( void )
11 {
12 /* initialize array of 3 pointers to functions that each take an
13 int argument and return void */
14 void (*f[ 3 ])( int ) = { function1, function2, function3 };
15
16 int choice; /* variable to hold user's choice */ Array of pointers to functions
17
18 printf( "Enter a number between 0 and 2, 3 to end: " );
19 scanf( "%d", &choice );
20

Sample Footer Text 10/9/24 58


21 /* process user's choice */

Function
22 while ( choice >= 0 && choice < 3 ) {
23

Pointers:
24 /* invoke function at location choice in array f and pass
25 choice as an argument */
Function called is dependent on use
Example-2
26 (*f[ choice ])( choice );
27
28 printf( "Enter a number between 0 and 2, 3 to end: ");
29 scanf( "%d", &choice );
30 } /* end while */
31
32 printf( "Program execution completed.\n" );
33
34 return 0; /* indicates successful termination */
35
36 } /* end main */
37
38 void function1( int a )
39 {
40 printf( "You entered %d so function1 was called\n\n", a );
41 } /* end function1 */
42
43 void function2( int b )
44 {
45 printf( "You entered %d so function2 was called\n\n", b );
46 } /* end function2 */

Sample Footer Text 10/9/24 59


Function
Pointers:
47
48 void function3( int c )

Example-2
49 {
50 printf( "You entered %d so function3 was called\n\n", c );
51 } /* end function3 */

Enter a number between 0 and 2, 3 to end: 0


You entered 0 so function1 was called

Enter a number between 0 and 2, 3 to end: 1


You entered 1 so function2 was called

Enter a number between 0 and 2, 3 to end: 2


You entered 2 so function3 was called

Enter a number between 0 and 2, 3 to end: 3


Program execution completed.

Sample Footer Text 10/9/24 60


Dynamic Memory Management
• Creating and maintaining dynamic data structures that grow and shrink at
execution time
• Allocate memory at execution time (malloc)
• Release memory no longer needed (free)
• malloc takes as parameter the number of bytes to allocate
• Returns a void pointer, NULL is allocation fails
• myVarPtr=(int *) malloc (sizeof(int));
• myArrPtr=(int *) malloc (sizeof(int)*10);
• The function free can be used to release the allocated memory. Takes the
memory address (pointer) as an argument.
• free(myArrPtr);

10/9/24 Sample Footer Text 61


Dynamic
Memory Mgmt:
Example

Sample Footer Text 10/9/24 62


•Reallocate memory
Dynamic
Memory Mgmt: ptr = realloc (ptr,newsize

Example

Sample Footer Text 10/9/24 63

You might also like