samedi 25 avril 2015

Are array memory addresses always in the order of least to greatest?


When I'm making a procedure with pointer arithmetic and !=, such as

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n; 
    while (arr != end && arr != --end) 
    {
         swap(arr,end);
         ++arr;
    }
}

I always take a lot of caution because if I write my procedure wrong then in a corner case the first pointer might "jump over" the second one. But, if arrays are such that

&arr[0] < &arr[1] < ... < &arr[n]

for any array arr of length n-1, then can't I just do something like

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n;
    if (arr == end) break;
    --end;
    while (arr < end)
    {
        swap(arr,end);
        ++arr; --end;
    }
}

since it's more readable? Or is there a danger looming? Aren't memory addresses just integral types and thus comparable with < ?


Aucun commentaire:

Enregistrer un commentaire