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.
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
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.
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
#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
.
#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
.
In this tutorial, we've learned how pointers can be used with arrays and strings in C++. The key points are:
Next, you should practice these concepts with different data types and operations. Also, explore how dynamic memory allocation works with pointers.
Here are some additional resources to help you understand the topic better:
- Pointers in C++
- Arrays as Pointers
- Strings and Pointers