15 ms·
The idiomatic way to get a pointer to one past the end of an array x with element-type foo is x + sizeof x / sizeof *x which is equivalent to (foo *)
by cygx 15y ago
The idiomatic way to get a pointer to one past the end of an array x with element-type foo is
x + sizeof x / sizeof *x
which is equivalent to
(foo *)((char *)x + sizeof x)
whereas
x + sizeof x
is equivalent to
(foo *)((char *)x + sizeof (foo) * sizeof x))
The expression
&x + 1
is not idiomatic as it has the type pointer-to-array-of-foo instead of pointer-to-foo.
As to your final question: Parameter declarations discard the size of array types - they are actually pointer-declarations in disguise.
To enforce a fixed array size, you need to declare a parameter of type pointer-to-array, eg
void bar(int (*arg)[42]);
which you'd have to call like this:
int x[42] = { 0 };
bar(&x);
- caf 15y agoYou can also get the "correct" type (type of &x[0]) by using: *(&x + 1) I would be hard-pressed to call that idiomatic, however.