ЁЯЦЗя╕П

Pointers in C++ Introduction and Operations

Jun 12, 2024

Pointers in C++

Introduction

  • In today's lecture, we will learn about pointers in C++.
  • A pointer is a variable that stores an address.

Basic Pointers

  • Definition of Pointers: A variable has an address in memory, which we can store in another variable.
  • Example: int a = 10; int* p = &a; // Pointer p will store the address of a
  • The dereferencing operator (*) is used to declare a pointer.
  • The address operator (&) gives the address of a variable.

Utility of Pointers

  • With pointers, we can access and modify the value of a variable without directly using the variable.
  • Example: *p = 20; // The value of a will now be 20

Pointer Arithmetic

  • Four types of arithmetic operations are possible on pointers: increment, decrement, addition, and subtraction.
  • Example: p++;
  • Here, p is an integer pointer, so p++ will point to the next memory location which is 4 bytes ahead.

Arrays and Pointers

  • The first element of an array is a pointer.
  • We can access array elements using pointers.
  • Example: int arr[] = {10, 20, 30}; int* p = arr; // p is now pointing to the first element of arr for(int i = 0; i < 3; i++) printf("%d ", *(p + i));

Pointers to Pointers

  • A pointer can point to another pointer.
  • Example: int a = 10; int* p = &a; int** q = &p; // q is a pointer pointing to p
  • Here, **q will access the value of a.

Call by Value and Call by Reference

  • Call by Value involves passing a copy of the variable, so the original variable value does not change.
  • Call by Reference involves passing the address of the variable, allowing changes to the original value.
  • Example (swap function): void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int main() { int x = 5, y = 10; swap(&x, &y); // The values of x and y will swap return 0; }

Conclusion

  • The importance and utility of pointers are evident in 'call by reference' and memory management.
  • In the next class, we will cover more examples and advanced topics involving pointers.

Note

  • Understanding pointers can sometimes be challenging, but with regular practice, it becomes easier.