Ahmed
Ahmed

Reputation: 184

Are C++ array items guaranteed to be in contiguous addresses?

In other words, say I have an array of objects Object foo[10]

And a function takes a pointer to one of them as an argument: func(&foo[0])

Should I be able to access the rest of the array inside of that function by calculating these offsets?

func(Object* a)
{
  Object* a0 = a;
  Object* a1 = a0 + sizeof(Object)
  Object* a2 = a0 + sizeof(Object)*2
}

Upvotes: 3

Views: 132

Answers (4)

eerorika
eerorika

Reputation: 238311

Are C++ array items guaranteed to be in contiguous addresses?

Yes.

Should I be able to access the rest of the array inside of that function by calculating these offsets?

Yes. In fact, this is an idiomatic way to iterate over array elements. Pointer to element of an array is an iterator.


Object* a0 = a;
Object* a1 = a0 + sizeof(Object)
Object* a2 = a0 + sizeof(Object)*2

In this example, a1 will not point to the next sibling of a0 unless the size of the object happens to be 1. Pointer arithmetic works in units of object size, not in units of bytes. In other words, to get pointer to the next element, you write a0 + 1. To get the element itself, you can combine pointer arithmetic and indirection by using the subscript operator: a0[1].

Upvotes: 0

Barmar
Barmar

Reputation: 780798

No, that won't work. When you perform arithmetic on pointers, it's done in units of the size of the type that it points to. So you don't need to multiply by sizeof(Object), that happens automatically; if you do it explicitly, you're multiplying twice.

Object *a0 = a; // points to a[0]
Object *a1 = a0 + 1; // points to a[1]
Object *a2 = a0 + 2; // points to a[2]

You would only multiply by sizeof if you first cast the pointer to char *.

Object *a1 = (Object *)((char *)a0 + sizeof(Object));
Object *a2 = (Object *)((char *)a0 + sizeof(Object) * 2);

Upvotes: 2

HolyBlackCat
HolyBlackCat

Reputation: 96053

Yes, elements are guaranteed to be contiguous.

But you don't need sizeof(Object). When adding a number to a pointer, that number is automatically multiplied by the size of the type the pointer points to. Similarly, when you subtract two pointers, the result is divided by the pointed type size.

You want this:

Object *a0 = a;
Object *a1 = a0 + 1;
Object *a2 = a0 + 2;

Upvotes: 7

Nathan Chappell
Nathan Chappell

Reputation: 2436

From the reference site:

A declaration of the form T a[N];, declares a as an array object that consists of N contiguously allocated objects of type T.

Also, in case there was any question (definition of object):

An object, in C++ , is a region of storage

As for the indirection (subscript), see the Built-in subscript operator

The built-in subscript expression E1[E2] is exactly identical to the expression *(E1 + E2)

Upvotes: 3

Related Questions