Basic Example using Pointer and Array in C++
Example Program : 1
This program demonstrates how to use arrays and pointers to display memory addresses.
- The program starts by declaring an array of float type with 3 elements named arr. Then a pointer to float type is declared named ptr.
- The program uses a for loop to display the memory addresses of each element of the array arr using the address-of operator &. The loop runs from i=0 to i<3 and prints the address of each element of the array using the format specifier %p.
- After that, the pointer ptr is assigned the address of the first element of the array arr. The program then uses another for loop to display the memory addresses of each element of the array using the pointer ptr. The loop runs from i=0 to i<3 and prints the address of each element of the array using the format specifier %p.
- Finally, the program returns 0 indicating successful execution.
Source Code
#include<iostream>
using namespace std;
int main()
{
float arr[3];
float *ptr;
cout<<"Displaying address using arrays: "<<endl;
for(int i=0;i<3;++i)
{
cout<<"&arr["<<i<<"] = "<<&arr[i]<<endl;
}
ptr=arr;
cout<<"\nDisplaying address using pointers: "<<endl;
for(int i=0;i<3;++i)
{
cout<<"ptr + "<<i<<" = "<<ptr+i<<endl;
}
return 0;
}
To download raw file
Click Here
Output
Displaying address using arrays:
&arr[0] = 0x7ffd0f0ca02c
&arr[1] = 0x7ffd0f0ca030
&arr[2] = 0x7ffd0f0ca034
Displaying address using pointers:
ptr + 0 = 0x7ffd0f0ca02c
ptr + 1 = 0x7ffd0f0ca030
ptr + 2 = 0x7ffd0f0ca034
Example Program : 2
The program demonstrates the use of pointers in C++ to access the memory locations of an array.
- In this program, an integer array var of size 3 is declared and initialized with values 10, 100, and 200. A pointer ptr is also declared to hold the memory address of the first element of the array var.
- The for loop is used to print the address and value of each element of the array var. Inside the loop, the address of the current element is printed using cout<<ptr. The value of the current element is printed using cout<<*ptr.
- After printing the address and value of the first element of the array var, the pointer ptr is incremented to point to the next element of the array. This process is repeated until all the elements of the array have been printed.
- At the end of the program, the control is returned to the operating system by return 0.
Source Code
#include<iostream>
using namespace std;
const int MAX = 3;
int main()
{
int var[MAX] = {10,100,200};
int *ptr;
ptr=var;
for(int i=0;i<MAX;i++)
{
cout<<"Address of var["<<i<<"] = ";
cout<<ptr<<endl;
cout<<"Value of var["<<i<<"] = ";
cout<<*ptr<<endl;
ptr++;
}
return 0;
}
To download raw file
Click Here
Output
Address of var[0] = 0x7fffd226f93c
Value of var[0] = 10
Address of var[1] = 0x7fffd226f940
Value of var[1] = 100
Address of var[2] = 0x7fffd226f944
Value of var[2] = 200