C++ Pointers and Arrays
Point to Every Array Elements
In C++, you can use a pointer to point to every element of an array. Here's an example:
int arr[5] = {1, 2, 3, 4, 5}; int* ptr = arr; // pointer to the first element of the array for(int i = 0; i < 5; i++) { cout << *ptr << " "; // print the value pointed to by ptr ptr++; // move the pointer to the next element of the array } // Output: 1 2 3 4 5Sowww:ecru.theitroad.com
In this example, we declare an integer array arr
of size 5 and initialize it with some values. We then declare a pointer ptr
and initialize it to point to the first element of the array using the address-of operator (&
). We then use a for
loop to iterate over each element of the array and print the value pointed to by the pointer ptr
. Finally, we increment the pointer ptr
to point to the next element of the array.
Array name used as pointer
In C++, the name of an array is used as a pointer to the first element of the array. Here's an example:
int arr[5] = {1, 2, 3, 4, 5}; cout << *arr << endl; // Output: 1 int* ptr = arr; cout << *ptr << endl; // Output: 1
In this example, we declare an integer array arr
of size 5 and initialize it with some values. We then use the dereference operator (*
) to print the value pointed to by the array name arr
, which is the first element of the array. We then declare a pointer ptr
and initialize it to point to the first element of the array using the array name arr
. We then use the dereference operator to print the value pointed to by the pointer ptr
, which is also the first element of the array.
Note that when you use the array name as a pointer, you cannot modify the value of the pointer. For example, the following code will give you a compilation error:
int arr[5] = {1, 2, 3, 4, 5}; arr++; // Error: invalid use of array with unspecified bounds
This is because the array name arr
is a constant pointer to the first element of the array, and cannot be modified.