Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a pointer to before the beginning of an array if I know only existing elements will be used?

I have a code in which I do something that looks like:

double computeSometing(const double * parameters)
{
  return useValues(parameters - 10); 
  // in this special case, useValues only uses values that are 
  // at least at parameters[0] or after
}

This looks bad, but this code is only called in circumstances in which I know that useValues is not going to use any value before the 10th (this is not always the case), so that all the values used are "inside" parameters. Is that undefined behaviour ? I know it just works on all the compilers/platforms I've used, but that does't make it defined.

I do that to avoid to copy the contents of parameters to a new array with 10 more elements, as this function is performance-sensitive.

like image 910
Vincent Fourmond Avatar asked Nov 22 '19 08:11

Vincent Fourmond


2 Answers

The subtraction has undefined behaviour.

[expr.add]:

If the expression P points to element x[i] of an array object x with n elements, [...] the expression P - J points to the (possibly-hypothetical) element x[i − j] if 0 ≤ i − j ≤ n; otherwise, the behavior is undefined.

Note that the act of producing the value is undefined in itself - you don't even need to use the result.

like image 64
molbdnilo Avatar answered Sep 28 '22 01:09

molbdnilo


No you can't.

Pointer arithmetic is only valid within arrays, with the exception that you can set a pointer to point one past the final element of an array, and for this purpose an object is considered to be a single element array. The behavior on reading such an out of range pointer (let alone dereferencing it) is undefined.

Can't you simply pass the array along with an offset (perhaps of type std::ptrdiff_t)?

like image 36
Bathsheba Avatar answered Sep 28 '22 03:09

Bathsheba