What is the advantage of using a function? |
One advantage would be to protect access, so you can't blow up or otherwise damage your program by trying to access an invalid element. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
// return pointer to element if index within array and there are
// at least enough elements as wanted; otherwise return NULL
int* access_array_at_elem(int* pelems, int size, int index, int size_wanted) {
if( (0 <= index) && (index < size) // index is within range
&& (size_wanted <= (size - index)) ) // there are enough elements
return &pelems[index];
return NULL; // or nullptr, in C++11
}
// I should have checked size_wanted was greater than zero,
// but it made the function look a bit messy. In practice I prefer
// to use an unsigned int for indices, so the checking of lower
// bounds is not be needed.
|
In your case, asking for a pointer to element 1024 or element -6 would cause problems. as would trying to access 74 elements from index 3. Similarly, vlad's strchr example prevents the pointer running off the end of the string (assumed to be in a valid buffer).
Note that providing a mechanism for element based access to the array is usually better than returning a pointer into the array. This is why (e.g.) std::vector and std::string provide operator[]. Using (e.g.) &vec[0] does allow you to get at the vector's buffer, but this should only be used to pass the vector or string's buffer to a C function (see PS).
Andy
PS Direct access to std::vector and std::string's buffer is possible, using (e.g.) &vec[0] or &str[0]. But this is not supposed to be used for general purposes: it is provided to allow these types to be uses with C functions, e.g. to populate the vector or string.
In the case of std::string, use of e.g. &str[0] to fill a string in with a C function is only officially supported (that is, is part of the C++ standard) as of C++11. Even though all major implementation of std::string already allow you to do this (apparently other parts of the standard make it had to do otherwise).