0

A colleague of mine asked this question: Array size in multidimensional array with pointers

The answers are all pretty definitive in that you cannot work out the size of an array that is referenced by a pointer.

My initial thought was to first dereference the pointer and then calculate the size of the array itself. Why would this not work? Does dereferencing the pointer not give you the full array?

Community
  • 1
  • 1
Jasarien
  • 58,279
  • 31
  • 157
  • 188
  • nope, just the first element in the array - which in of itself is meaningless in this context...Size is not a piece of information that is *embedded* in the underlying representation... – Nim Feb 13 '13 at 10:26
  • It's like unwind said. If you want to retain size information, store it. Or use a convention (such as the last element is always nullified). – StoryTeller - Unslander Monica Feb 13 '13 at 10:28
  • You may find this useful http://stackoverflow.com/a/5655614/1458030 – qPCR4vir Feb 13 '13 at 10:42

2 Answers2

3

There is no "full array" in C, at least not as you seem to expect there to be.

An array can always be represented as a pointer to the first element, together with information about the array's layout.

This information is not available at runtime, it's part of the type for actual arrays (like int foo[6][2][12]) so the compiler can just use that knowledge directly when generating code to access elements. As pointed out by Lundin, the exception is variable-length arrays (introduced in C99). For those, the compiler must add run-time code to make sizeof work.

If you pass foo to a function taking int *, there's no way to magically re-create the dimensionality data from that. All pointers to int look the same, you can pass &foo[0][0][0] or just the address of a plain int.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Unfortunately there is no way in C to determine the size of an array. Arrays are just pointers to a memory location. You have to know how much memory in that location is part of an array.

That's why most methods from the standard library which use arrays either need nul-terminated arrays, or an additional argument telling them their length.

Philipp
  • 67,764
  • 9
  • 118
  • 153