Pointers and Arrays

by Shabbir on May 6, 2008

in C/C++

In this article we will explain moving the pointer through an array. It's simple but sometimes confusing.
So try these simple examples in your unmanaged C++ project.

Creating an array and assigning a pointer to it

int arr[4];
int *ptr = arr;  //[*][ ][ ][ ] Points at the first element of the array

When using pointers and arrays, we don't need to use ampersand (&) to assign the address of the array to the pointer. It returns the address of the first array element. But if we want to point at other element (not the first) we must use an ampersand.

Then we assign a value to the first element

*ptr = 2;        //1st

Moving the pointer two places forward (his address will increase by the size of integer which is 4 bytes, in this case 2x4), now the pointer points at the third element, and we assign a value to it (6)

ptr += 2;        //[ ][ ][*][ ]
*ptr = 6;        //3rd

Other way to point to an element, the way with ampersand. We now point at the last element, the fourth, and assigning a value to it (8)

ptr=&arr[3];     //[ ][ ][ ][*]
*ptr=8;          //4th

Not moving the pointer but pointing two places left from the pointer, and then assigning a value

*(ptr - 2) = 4;  //2nd

Print the value which ptr points on

cout << *ptr << endl;

It will be printed "8", that shows that the pointer points to the last element.

Now print the array

for(int i = 0 ;i < 4 ;i++)
	cout << arr[i] << endl;

Printed values: 2, 4, 6, 8.

Let's see how to print using the pointer without moving it, but first, make the pointer point on the first element

ptr = arr;

then

for(int i = 0 ;i < 4 ;i++)
	cout << *(ptr + i) << endl;

or printing by moving the pointer

for(int i = 0 ;i < 4 ;i++)
	cout << *ptr++ << endl;

Sharing is Caring...

Other Related Posts:

  1. Pointers
  2. Read From File In C++
  3. Functions in C++
  4. Write To File In C++
  5. Safe Programming

Leave a Comment

Spam protection by WP Captcha-Free

Previous post:

Next post:

    About the Author

  • author photo

    My Name is Shabbir Bhimani and I am developer by profession in the field of applications, web and database. Currently doing full time online marketing and like to share my experiences on how you can make money online @ CodeItWell.com. Read more ...


    See how you can get in touch with me.