Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining a pointer to the end of an array

I use the following template to obtain a pointer pointing after the last element of an array:

template <typename T, size_t n>
T* end_of(T (&array)[n])
{
    return array + n;
}

Now I seem to remember that there was some problem with this approach, but I cannot remember what it was. I believe it had something to with the choice of the type parameters or function parameters, but I'm not sure. So just as a sanity check, do you see any problems with the above code? Small usage test:

int test[] = {11, 19, 5, 17, 7, 3, 13, 2};
std::sort(test, end_of(test));
like image 779
fredoverflow Avatar asked Jan 21 '11 13:01

fredoverflow


People also ask

How do you define an end of an array?

C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.

Can we address one element beyond the end of an array?

It does, however, allow a pointer to point at one element beyond the end of the array. The distinction is important. Thus, this is OK: char array[N]; char *p; char *end; for (p = array, end = array + N; p < end; ++p) do_something(p);


1 Answers

Your proposal is not necessarily evaluated at compile time, it depends on optimisation. The following is calculated at compile time:

template <typename T, size_t N> char (&array(T(&)[N]))[N];

int main()
{
  int myArray[10];

  std::cout << sizeof array(myArray) << std::endl;

  return 0;
}

It works by creating an array type of char which is the same number of elements as the given array. sizeof always returns size in number of chars.

like image 106
T33C Avatar answered Oct 10 '22 18:10

T33C