3

Suppose there exists an array, A, such that its elements are of struct Element and I am told that the struct Element is packed with no padding.

If I am given pointers to the first and last element in A, can I determine the number of elements in A based on the address of the pointers and amount of memory an Element takes up? Or does the structure of an array in memory not work like that.

My thought is if the pointers I'm given are Element* start and Element* finish...

number of elements = (finish - start) / sizeof(Element)

Is this logical thinking?

2 Answers 2

8

If you have:

Element* start; // first element
Element* finish; // last element

Then:

numElements = finish - start + 1;
  1. If finish is like an end in STL, you do not have the +1.
  2. Because of pointer arithmetic, you do not have to divide by sizeof(Element)

With regard to considering whether there might be padding at the structure end, as Billy indicated, sizeof already contains that, as will pointer arithmetic. from the C++14 final draft:

N3797/5.3.3/2 [ sizeof ]

When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.

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

4 Comments

Note that the "finish is one past the end" behavior in the STL allows the range to represent the empty range start == end.
RE: Your update: C requires that no padding be inserted between objects, and that that any necessary padding to align them in an array be included in their sizeof; e.g. sizeof(struct{int I; char c;}} is typically sizeof(int) * 2
@BillyONeal. Thanks, sounds right; C++ has to be the same? I was trying to remember the guarantees.
Yep; as far as I know the requirement is the same there
0

When you use pointer arithmetic, you can say that the "unit" is the size of one element of the type pointed to.

I.e. if you have Element* start pointing to the 0-th element of an array, start + 1 will point to the 1-st element of that array.

So, when you use finish - start, you already get the number of elements between them, and there is no need to divide by sizeof(Element).

1 Comment

Note: this behaviour of pointer arithmetic can give surprising results. For example, a pointer to an array and a pointer to an array's 0th element effectively point to the same place, but incrementing the former will make you skip past the array, and incrementing the latter will land you on the array's 1st element.

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.