|
|
Subscribe / Log in / New account

Variable-length arrays and the max() mess

Variable-length arrays and the max() mess

Posted Mar 22, 2018 13:13 UTC (Thu) by HelloWorld (guest, #56129)
In reply to: Variable-length arrays and the max() mess by dtlin
Parent article: Variable-length arrays and the max() mess

By the way, is it allowed to have a pointer that is one past the end of a variable that isn't an array? Something like this:

void print_ints(const int *begin, const int *end) {
  for (; begin < end; ++begin) {
    printf("%d\n", *begin);
  }
}

int main() {
  int i = 42;
  print_ints(&i, &i + 1);
  return 0;
}


to post comments

Variable-length arrays and the max() mess

Posted Mar 22, 2018 13:17 UTC (Thu) by HelloWorld (guest, #56129) [Link] (2 responses)

When compiling this with -fsanitize=address, it doesn't complain, so it's probably OK… but still, i isn't technically an array, right?

Variable-length arrays and the max() mess

Posted Mar 22, 2018 15:08 UTC (Thu) by excors (subscriber, #95769) [Link] (1 responses)

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf says "For the purposes of these operators ['+' and '-'], a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.", immediately before defining the rules for pointer arithmetic (where it's undefined behaviour unless "both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object"). So it sounds to me like your code is fine.

Variable-length arrays and the max() mess

Posted Apr 12, 2018 23:24 UTC (Thu) by HelloWorld (guest, #56129) [Link]

Ah right, that is the part of the spec I was looking for, thanks!


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds