how to make a pointer point to a the last value in an array
To make a pointer point to the last value in an array in C++, you can follow these steps:
- Declare an array: Start by declaring an array of a specific data type. For example, you can declare an integer array as follows:
int arr[] = {1, 2, 3, 4, 5};
- Calculate the size of the array: Determine the size of the array using the
sizeof
operator. This will give you the total number of elements in the array.
int size = sizeof(arr) / sizeof(arr[0]);
- Create a pointer variable: Declare a pointer variable of the same data type as the array. In this case, the array is of type
int
, so we declare anint*
pointer.
int* ptr;
- Assign the address of the last element: Set the pointer variable to point to the last element of the array. To do this, you can use the index
size - 1
to access the last element, and then use the&
operator to get its address.
ptr = &arr[size - 1];
Now, the pointer ptr
is pointing to the last element of the array arr
. You can use this pointer to perform operations on the last element, such as dereferencing it or modifying its value.
Here's the complete code snippet:
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int* ptr;
ptr = &arr[size - 1];
std::cout << "Value of the last element: " << *ptr << std::endl;
return 0;
}
This code snippet demonstrates how to make a pointer point to the last value in an array and prints the value of the last element using the pointer.