# It is just not clicking in my head (Output an array via pointer in reverse)

• 10-21-2005
It is just not clicking in my head (Output an array via pointer in reverse)
So this is one of thoose things that is not clicking in my head.

I am trying to write a function using "pointer notation" that will write out the elements of an array of int in reverse order. I know this has to be done via a for loop but I am a little lost when it comes to the "pointer notation". When assinging the address of a pointer to an array it assigns it to the first element [0] correct? Anyways I would appreciate it if someone could offer up and example.

Thanks

• 10-21-2005
Salem
for ( p = &array[n-1] ; p >= array ; p-- )
• 10-21-2005
Quote:

Originally Posted by Salem
for ( p = &array[n-1] ; p >= array ; p-- )

What are the declarations in this? Is p the pointer?

So p = the address of the array, correct?

What is n? The element of the array?

Why n - 1? This has something to do with the fact that arrays actually start at 0 correct?

Thanks

• 10-21-2005
Salem
So p = the address of the array, correct?
p is a pointer to an element of the array. If you have T array[n] then it's T *p
• 10-21-2005
dwks
Quote:

Why n - 1? This has something to do with the fact that arrays actually start at 0 correct?
Exactly:
Code:

```int a[10]; /* printf("%i\n", a[10]); /* out of bounds */ printf("%i\n", a[9]); /* 9 is the last element . . . n (10) - 1 */```
• 10-21-2005
7stud
Quote:

What are the declarations in this?
They were left out for brevity.

n=size of the array. If you have the array:
Code:

`int myArray[] = {10, 20, 30};`
the size of the array is 3 but the valid index numbers are:

myArray[0] = 10
myArray[1] = 20
myArray[2] = 30

An array name is like a pointer to the first element. So, you can set a pointer to the first element like this:
Code:

```int* p = myArray; cout<<*p<<endl; //10```
Or, you can set the pointer to point to other elements of the array:
Code:

```p = &myArray[2]; //"p is equal to the address of myArray[2]" cout<<*p<<endl; //30```
Pointer arithmetic allows you to move the pointer along the array with the increment operator(++) or the decrement operator(--). Since you want to output the elements in reverse order, setting a pointer to the end of the array, and then decrementing that pointer everytime through a for-loop to move it along the array seems like a good approach.