2

In many code examples I find, they use "&Array[0]" if an array has to be passed to a function. Is there any reason to do so ? They could simply write "Array".

7
  • 3
    It is more consistent with the convention when indexing the array i.e. same as doing &array[n]. Plus often people have a hard time learning that the name of array evaluates to address of the first element. Commented Apr 10, 2014 at 3:20
  • There's no good reason and in fact I'd consider it an error. Commented Apr 10, 2014 at 3:20
  • @Dikesh Check the tags. It's C, not C++. Commented Apr 10, 2014 at 3:24
  • & "the address of" Array "in an array" [0] "the first element" - you answer your own question :) Commented Apr 10, 2014 at 3:28
  • 1
    Additionally, i would caution you to go through stackoverflow.com/q/14955574/986760. Make sure you understand they are same ONLY in above situation and not in all cases. A quick example, if you pass both of these to sizeof(), result would be different. One returns size of array in bytes vs the other returns size of pointer. Hope that helps Commented Apr 10, 2014 at 3:32

1 Answer 1

4

This is a pure style issue, and you should just do whatever your dev team prefers. Personally I like to use plain old Array and if I want to offset by n elements I would do Array + n. But some people find that confusing and use &Array[n], even when n == 0.

In defense of the other side the Array + n syntax requires you to know more about C in order to understand it. It involves both arrays degenerating into pointers, and also pointer arithmetic. But in my view, C programmers need to know all that stuff anyway, it's not a complicated language.

Sign up to request clarification or add additional context in comments.

2 Comments

"But in my view, C programmers need to know all that stuff anyway" - Agreed. If you're working on a real project and don't know the semantics of arrays then you're already in a really bad spot. Production code should not be catered to beginners.
Having programmed in C for almost a decade, (7+ years in industry) I would also argue that if i see it written that way (&arr[0]), the first thing that comes to mind is, whether it is written by some one new to C? May be they have only read the chapter on arrays and not pointers yet? I really don't recall ever seeing any good open source / professional c code which indexes the first element that way. Would love to see an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.