Pointers in C++ object oriented programming

Ahmad177077 28 views 22 slides Dec 14, 2024
Slide 1
Slide 1 of 22
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22

About This Presentation


Pointers in C++ are variables that store the memory address of another variable. They are powerful tools that allow you to directly access and manipulate memory, making them essential in systems programming, dynamic memory allocation, and data structures.


Slide Content

Pointers in C++ Ahmad Baryal Saba Institute of Higher Education Computer Science Faculty Nov 18, 2024 1

Table of contents Introduction to pointers How to use pointers References and Pointers Array Name as Pointers Pointer Expressions and Pointer Arithmetic Advanced Pointer Notations Pointers and String literals Pointers to pointers Void Pointers, Invalid Pointers and NULL Pointers Advantage of pointer 2

C++ Pointers The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. The symbol of an address is represented by a pointer. In addition to creating and modifying dynamic data structures, they allow programs to emulate call-by-reference. One of the principal applications of pointers is iterating through the components of arrays or other data structures. The pointer variable that refers to the same datatype as the variable you're dealing with, has the address of that variable set to it (such as an int or string). 3 Syntax datatype * var_name ;    int  * ptr ;    //  ptr  can point to an address which holds  int  data    

How to use a pointer? Establish a pointer variable. employing the unary operator (&), which yields the address of the variable, to assign a pointer to a variable's address. Using the unary operator (*), which gives the variable's value at the address provided by its argument, one can access the value stored in an address. Since the data type knows how many bytes the information is held in, we associate it with a reference. The size of the data type to which a pointer points is added when we increment a pointer. 4

Usage of pointer There are many usage of pointers in C++ language. 1) Dynamic memory allocation In C++ language, we can dynamically allocate memory using malloc() and calloc () functions where pointer is used. 2) Arrays, Functions and Structures Pointers in C++ language are widely used in arrays, functions and structures. It reduces the code and improves the performance. 5

Symbols used in pointer 6

Declaring a pointer The pointer in C++ language can be declared using ∗ (asterisk symbol). int  ∗   a; //pointer to  int      char  ∗  c; //pointer to char     Pointer Example: Let's see the simple example of using pointers printing the address and value. 7 #include < iostream > using namespace std ; int main() { int number=30; int ∗ p; p=&number;//stores the address of number variable cout <<"Address of number variable is:"<<&number<< endl ; cout <<"Address of p variable is:"<<p<< endl ; cout <<"Value of p variable is:"<<*p<< endl ; return 0; }

Array Name as Pointers An  array  name contains the address of the first element of the array which acts like a constant pointer. It means, the address stored in the array name can’t be changed. For example, if we have an array named val then  val  and  & val [0]  can be used interchangeably.  8 void geeks() { // Declare an array int val [3] = { 5, 10, 20 }; // declare pointer variable int * ptr ; // Assign the address of val [0] to ptr // We can use ptr =& val [0];(both are same) ptr = val ; cout << "Elements of the array are: "; cout << ptr [0] << " " << ptr [1] << " " << ptr [2]; } // Driver program int main() { geeks(); }

Pointer Expressions and Pointer Arithmetic A limited set of  arithmetic  operations can be performed on pointers which are: incremented ( ++ ) decremented ( — ) an integer may be added to a pointer ( + or += ) an integer may be subtracted from a pointer ( – or -= ) difference between two pointers (p1-p2) 9

Example 10 void geeks() { int v[3] = { 10, 100, 200 }; int * ptr ; // Assign the address of v[0] to ptr ptr = v; for ( int i = 0; i < 3; i ++) { cout << "Value at ptr = " << ptr << "\n"; cout << "Value at * ptr = " << * ptr << "\n"; // Increment pointer ptr by 1 ptr ++; } } int main() { geeks(); } Value at ptr = 0x7ffe5a2d8060 Value at * ptr = 10 Value at ptr = 0x7ffe5a2d8064 Value at * ptr = 100 Value at ptr = 0x7ffe5a2d8068 Value at * ptr = 200 Output:

References and Pointers There are 3 ways to pass C++ arguments to a function: Call-By-Value Call-By-Reference with a Pointer Argument Call-By-Reference with a Reference Argument In C++, function arguments can be passed in different ways, providing flexibility in how data is accessed and modified within functions. Two common methods are using references and pointers. This section explores three ways to pass arguments to a function: Call-By-Value, Call-By-Reference with a Pointer Argument, and Call-By-Reference with a Reference Argument. 11

References and Pointers 1. Call-By-Value in C++ Function Arguments In C++, Call-By-Value is a method of passing function arguments where the actual value of the variable is copied into the function parameter. This example illustrates how modifications inside the function do not affect the original value. 12 #include < iostream > using namespace std ; // Function prototype void squareByValue ( int x); int main() { int number = 5; cout << "Original value: " << number << endl ; // Calling the function with a value squareByValue (number); cout << "Value after function call: " << number << endl ; return 0; } // Function definition void squareByValue ( int x) { x = x * x; cout << "Value inside function: " << x << endl ; }

References and Pointers 2. Call-By-Reference with a Pointer Argument in C++ Function Arguments Call-By-Reference with a Pointer Argument in C++ allows a function to modify the original value by passing the address of the variable. This example demonstrates how changes made inside the function affect the original value through a pointer. 13 #include <iostream> using namespace std; // Function prototype void squareByReference(int *ptr); int main() { int number = 5; cout << "Original value: " << number << endl; // Calling the function with a pointer to the variable squareByReference(&number); cout << "Value after function call: " << number << endl; return 0; } // Function definition void squareByReference(int *ptr) { *ptr = (*ptr) * (*ptr); cout << "Value inside function: " << *ptr << endl; }

References and Pointers 3. Call-By-Reference with a Reference Argument in C++ Function Arguments Call-By-Reference with a Reference Argument in C++ provides a cleaner syntax than using pointers. This example demonstrates how changes made inside the function directly affect the original variable. 14 #include <iostream> using namespace std; // Function prototype void squareByReference(int &ref); int main() { int number = 5; cout << "Original value: " << number << endl; // Calling the function with a reference to the variable squareByReference(number); cout << "Value after function call: " << number << endl; return 0; } // Function definition void squareByReference(int &ref) { ref = ref * ref; cout << "Value inside function: " << ref << endl; }

Advanced Pointer Notation Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration. int nums [2][3] = { { 16, 18, 20 }, { 25, 26, 27 } }; In general , nums [ i ][ j ] is equivalent to *(*( nums+i )+j) 1. Using Array Notation: nums [ i ][j] accesses the element at the ith row and jth column of the array. 2. Using Pointer Notation: *(*( nums + i ) + j) is an equivalent expression using pointer notation. It can be interpreted as follows: nums + i: This gives the address of the ith row. *( nums + i ): Dereferencing this gives the array at the ith row. *( nums + i ) + j: This gives the address of the jth element in the ith row. *(*( nums + i ) + j): Finally, this dereferences that address to get the value at the ith row and jth column. 15

Advanced Pointer Notation Example 16 In this C++ example, a two-dimensional array named nums is declared and initialized with integer values. The program demonstrates two ways to access a specific element in this array: Array Notation: The syntax nums [ i ][j] is used, where i represents the row index, and j represents the column index. This is a standard way of accessing elements in a two-dimensional array. Pointer Notation: The equivalent expression *(*( nums + i ) + j) is used. This involves pointer arithmetic where nums + i gives the address of the ith row, *( nums + i ) dereferences that address, and *( nums + i ) + j gives the address of the jth element in the ith row. Finally, *(*( nums + i ) + j) dereferences that address to obtain the value. Output: Array Notation: 27 Pointer Notation: 27

Pointers and String literals 17 String literals are arrays containing null-terminated character sequences. String literals are arrays of type character plus terminating null-character, with each of the elements being of type const char (as characters of string can’t be modified). const char* ptr = "geek"; This declares an array with the literal representation for “geek”, and then a pointer to its first element is assigned to ptr . If we imagine that “geek” is stored at the memory locations that start at address 1800, we can represent the previous declaration as:  As pointers and arrays behave in the same way in expressions, ptr can be used to access the characters of a string literal. For example: char x = *(ptr+3); char y = ptr [3]; Here, both x and y contain k stored at 1803 (1800+3).

Pointers to pointers 18 In C++, we can create a pointer to a pointer that in turn may point to data or another pointer. The syntax simply requires the unary operator (*) for each level of indirection while declaring the pointer. char a; char *b; char **c; a = 'g'; // Assign the character 'g' to variable a b = &a; // b is a pointer that points to the address of a c = &b; // c is a pointer to a pointer, and it points to the address of b Here b points to a char that stores ‘g’ and c points to the pointer b.

Void Pointers 19 This is a special type of pointer available in C++ which represents the absence of type. Void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties). This means that void pointers have great flexibility as they can point to any data type. There is a payoff for this flexibility. These pointers cannot be directly dereferenced. They have to be first transformed into some other pointer type that points to a concrete data type before being dereferenced.

Invalid pointers 20 A pointer should point to a valid address but not necessarily to valid elements (like for arrays). These are called invalid pointers. Uninitialized pointers are also invalid pointers. int *ptr1; int arr [10]; int *ptr2 = arr+20; Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds of arr so it also becomes an invalid pointer. (Note: invalid pointers do not necessarily raise compile errors)

NULL Pointers & Advantages of Array 21 A  null pointer  is a pointer that point nowhere and not just an invalid address. Following are 2 methods to assign a pointer as NULL; int *ptr1 = 0; int *ptr2 = NULL; Advantages of Pointers: Pointers reduce the code and improve performance. They are used to retrieve strings, trees, arrays, structures, and functions. Pointers allow us to return multiple values from functions. In addition to this, pointers allow us to access a memory location in the computer’s memory.

Any Question? 22
Tags