0

I’m learning C++, and I’m having some trouble in understanding C arrays in depth. I’ve used them in many programs without any problem believing that they just were pointers to their first element with a nice syntax to do pointer arithmetics... but they aren’t, right?

As far as my current understanding goes, arrays are of type someType[someLength] while pointers are of type someType*, so they are clearly different. But some confusion for most beginners is made by the fact that arrays passed by value or pointer to functions “decay” into pointers to their first element, which is also the address of the array itself. Is this correct (aside being obviously incomplete)?

Now, my actual question(s), what are exactly arrays?
Why is it useful to have distinct types for array, pointers to first member of array and pointers to arrays? And since that clearly has to be useful for some reason, why can arrays implicitly decay? (or is this decay considered explicit?)
How does an array of n elements of type t differ from a struct whit n members of type t and nothing else? (I know they are different, but I think I only see some of the differences)

noearchimede
  • 188
  • 9
  • http://eel.is/c++draft/dcl.array – Henri Menke Mar 13 '18 at 00:35
  • Basically, pointers in C have a type so that the compiler knows the size of one element, so if p points to a thing, p+1 points to the next thing in memory. As array is a block of memory for things, so a[1] is just shorthand for *(a+1). Array types need a length primarily so that a pointer-to-array has a size for doing the math on a[1][1]. – Lee Daniel Crocker Mar 13 '18 at 00:36
  • 1
    "why can arrays implicitly decay?" - so that B code could be compiled as C with minimal changes – M.M Mar 13 '18 at 00:58
  • "How does an array of n elements of type t differ from a struct whit n members of type t and nothing else? " - the array is guaranteed to be contiguous and the syntax to iterate over it is nicer – M.M Mar 13 '18 at 00:59

0 Answers0