Using Pointers with Arrays and Strings

Tutorial 5 of 5

1. Introduction

In this tutorial, we'll explore how to use pointers with arrays and strings in C++, an important concept in the realm of programming. By the end of this guide, you'll be able to declare pointers, associate them with arrays and strings, and access or manipulate data using these pointers.

This tutorial assumes that you have a basic understanding of C++ programming, including variables, data types, arrays, and the basics of pointers.

2. Step-by-Step Guide

2.1 Pointer Basics

A pointer is a variable that stores the memory address of another variable. Pointers are declared by using the asterisk (*) before the variable name.

int *p; // declares a pointer to an integer
char *c; // declares a pointer to a character

2.2 Arrays and Pointers

In C++, the name of an array is a constant pointer to the first element of the array. Thus, if arr is an array, arr and &arr[0] are equivalent.

int arr[] = {10, 20, 30};
int *p = arr; // assigns the address of the first element of arr to p

We can use the pointer p to access and manipulate the array elements.

2.3 Strings and Pointers

C++ treats strings as arrays of characters (ending with a null character '\0'). So, pointers can also be used to manipulate strings.

char str[] = "Hello";
char *p = str; // assigns the address of the first character of str to p

3. Code Examples

3.1 Using Pointers with Arrays

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *p = arr;

    for(int i = 0; i < 5; i++) {
        cout << *(p + i) << " "; // accesses array elements using pointer arithmetic
    }

    return 0;
}

This code should output: 10 20 30 40 50.

3.2 Using Pointers with Strings

#include <iostream>
using namespace std;

int main() {
    char str[] = "Hello";
    char *p = str;

    while(*p != '\0') { // loop until the end of the string
        cout << *p; // print each character
        p++; // move the pointer to the next character
    }

    return 0;
}

This code should output: Hello.

4. Summary

In this tutorial, we've learned how pointers can be used with arrays and strings in C++. The key points are:

  • The name of an array is a pointer to its first element.
  • We can manipulate array elements or string characters using pointers.
  • We can increment or decrement pointers to traverse arrays or strings.

Next, you should practice these concepts with different data types and operations. Also, explore how dynamic memory allocation works with pointers.

5. Practice Exercises

  1. Write a program to reverse an array using pointers.
  2. Write a program to count the length of a string using a pointer.
  3. Write a program to copy one string to another using pointers.

Here are some additional resources to help you understand the topic better:
- Pointers in C++
- Arrays as Pointers
- Strings and Pointers