Pointers store the memory location or address of variables. In other words, pointers reference a memory location and obtaining the value stored at that memory location is known as dereferencing the pointer.
A program that uses pointers to access a single element of an array is given as follows −
Example
#include <iostream> using namespace std; int main() { int arr[5] = {5, 2, 9, 4, 1}; int *ptr = &arr[2]; cout<<"The value in the second index of the array is: "<< *ptr; return 0; }
nother program in which a single pointer is used to access all the elements of the array is given as follows.
Example
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[0];
cout<<"The values in the array are: ";
for(int i = 0; i < 5; i++) {
cout<< *ptr <<" ";
ptr++;
}
return 0;
}
Output
The values in the array are: 1 2 3 4 5
In the above program, the pointer ptr stores the address of the first element of the array. This is done as follows.
int *ptr = &arr[0];
After this, a for loop is used to dereference the pointer and print all the elements in the array. The pointer is incremented in each iteration of the loop i.e at each loop iteration, the pointer points to the next element of the array. Then that array value is printed. This can be seen in the following code snippet.
note:-it's just a sudo code if its not executing on your device make some changes in the further code this is only for understanding logic.
thankyou for visiting us stay tuned for learning and more intresting u can ask questions in comment section check other blogs for more info. comment mail for compitative cading thankyou.👍😎🙏
0 Comments