Programming with Passion

Make the best out of everything.

Saturday, 26 March 2016

Pointer and Arrays

Example 2: Pointer and Arrays

C++ Program to display address of array elements using pointer notation.
#include <iostream>
using namespace std;

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

    return 0;
}
Output
Displaying address using pointers notation: 
0x7fff5fbff8a0
0x7fff5fbff8a4
0x7fff5fbff8a8
0x7fff5fbff8ac
0x7fff5fbff8b0
You know that, pointer ptr holds the address and expression *ptr gives the content in that address. Similarly, *(ptr + 1) gives the content in address ptr + 1. Consider this code below:
int p[5] = {3, 4, 5, 5, 3};
  • &p[0] is equal to p and *p is equal to p[0]
  • &p[1] is equal to p+1 and *(p+1) is equal to p[1]
  • &p[2] is equal to p+2 and *(p+2) is equal to p[2]
  • &p[i] is equal to p+i and *(p+i) is equal to p[i]

No comments:

Post a Comment