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


when i'm making procedure pointer arithmetic , !=, 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 take lot of caution because if write procedure wrong in corner case first pointer might "jump over" second one. but, if arrays such

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

for array arr of length n-1, can't 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 there danger looming? aren't memory addresses integral types , comparable < ?

the relational operators defined work correctly when comparing addresses within same array (in fact, objects of class type, there guarantees memory layout also) including one-past-the-end pointer.

however, if "jump over" end-of-array pointer, no longer comparing 2 addresses within same array, , behavior undefined. (one cause might in fact experience wraparound when pointer arithmetic outside objects, ub not restricted).

your case fine concerning jump-over, because end pointer isn't one-past-the-end of array, since @ least 1 --end. empty array, --end moves outside array, issue, test separately.

conclusion: second code valid.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -