pointing to an element inside an array

If I have an array of const doubles and I want to create a pointer which points to the nth element in the array, how would I do this? What about the 0th element in the array? Could I create a for loop that loops from the 0th element of the array to the nth element of the array if I had those two pointers?
You can create const double pointers to the elements in the array

1
2
3
4
const double array[4] = {1.2, 3.0, 5.0, 8.3};
const double *ptr = array; //pointer to the base of the array (first element)
std::cout << *ptr << endl; //prints 1.2
std::cout << *(++ptr) <<endl; //prints 3.0  
alright thanks. But now what if I needed to point to the 90th element in the array?
In expression array is converted to the pointer to its first element.

1
2
3
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int *p = a;

To get address of the nth element it is enough to add integer value n to array name

p += n;

The loop can be written for example the following way

1
2
3
4
5
6
for ( int *p = a; p != a + n + 1; ++p )
{
   std::cout << *p << ' ';
}

std::cout << std::endl;
simple access the 90th element of the array, and get its address using the address of operator &, you can then assign that to a pointer.
simple access the 90th element of the array, and get its address using the address of operator &, you can then assign that to a pointer.


This is what I was thinking....but what would the syntax for this be?
closed account (zb0S216C)
hopesfall wrote:
If I have an array of const doubles and I want to create a pointer which points to the nth element in the array, how would I do this?


1
2
const double Double_Array[10] = { /* Values... */ };
const double *End( Double_Array + 9 );


hopesfall wrote:
What about the 0th element in the array?

The first?

 
const double *Begin( Double_Array );


hopesfall wrote:
Could I create a for loop that loops from the 0th element of the array to the nth element of the array if I had those two pointers?

Yes:

1
2
3
4
for( ; Begin <= End; ++Begin )
{
    // Do something...
}

Edit:

I should say that the pointer must be constant if the array is an array of constant objects. If the pointer wasn't constant, it would break the rules of const, which the compiler frowns upon.

Wazzak
Last edited on
Topic archived. No new replies allowed.