Programming with Passion

Make the best out of everything.

Saturday, 26 March 2016

C++ Pointers and Arrays

Example 1: C++ Pointers and Arrays

C++ Program to display address of elements of an array using both array and pointers
#include <iostream>
using namespace std;

int main() {
    float a[5];
    float *ptr;
    
    cout << "Displaying address using arrays: "<<endl;
    for (int i = 0; i < 5; ++i) {
        cout << "&a[" << i << "] = " << &a[i] <<endl;
    }

    ptr = a;   // ptr = &a[0]
    cout<<"\nDisplaying address using pointers: "<< endl;
    for (int i = 0; i < 5; ++i) {
        cout << "ptr + " << i << " = "<<ptr+i <<endl;
    }

    return 0;
}
Output
Displaying address using arrays: 
&a[0] = 0x7fff5fbff880
&a[1] = 0x7fff5fbff884
&a[2] = 0x7fff5fbff888
&a[3] = 0x7fff5fbff88c
&a[4] = 0x7fff5fbff890

Displaying address using pointers: 
ptr + 0 = 0x7fff5fbff880
ptr + 1 = 0x7fff5fbff884
ptr + 2 = 0x7fff5fbff888
ptr + 3 = 0x7fff5fbff88c
ptr + 4 = 0x7fff5fbff890
In the above program, different pointer is used for displaying the address of array elements. But, array elements can be accessed using pointer notation (by using same array name). For example:
int p[3];

&p[0] is equivalent to p
&p[1] is equivalent to p+1
&p[2] is equivalen to p+2

No comments:

Post a Comment