Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Same here. For the cases where you really do want to find the first memory address past the end of the array (if you're doing some hackish memory management, probably), I think x + sizeof(x) is more idiomatic than &x+1, because it avoids that particular arrays-are-almost-pointers weirdness in favor of regular pointer arithmetic.

Though I used to program a lot of C, I'm not a C wizard by a longshot, so I might be wrong. Are there cases where using expressions based on &x, where x is an array name, is idiomatic C?

edit: Stupid mistake, see cygx's reply (sizeof(x) gives the size of the array x in bytes, not in elements).



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);


You can also get the "correct" type (type of &x[0]) by using:

  *(&x + 1)
I would be hard-pressed to call that idiomatic, however.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: