56

If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?

e.g.

vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p
Ferruccio
  • 98,941
  • 38
  • 226
  • 299

6 Answers6

72

Yes, that is a valid assumption (*).

From the C++03 standard (23.2.4.1):

The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

(*) ... but watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Eclipse
  • 44,851
  • 20
  • 112
  • 171
  • 1
    If you're using a draft standard, or anything not yet ratified and official, please say so. I couldn't find anything like that in the current standard. – David Thornley Jan 13 '09 at 21:49
  • 5
    In the C++0x draft, it's 23.2.5.1, and in C++03, It's 23.2.4.1. The wording is not in the C++98 standard. I'm looking at ISO/IEC 14882:2003(E) – Eclipse Jan 13 '09 at 22:11
  • 1
    It was added later in the Technical Corrigendum. – Vadim Ferderer Jan 22 '09 at 20:33
27

The C++03 standard added wording to make it clear that vector elements must be contiguous.

C++03 23.2.4 Paragraph 1 contains the following language which is not in the C++98 standard document:

The elements of a vector are stored contiguously, meaning that if v is a vector<T, Allocator> where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

Herb Sutter talks about this change in one of his blog entries, Cringe not: Vectors are guaranteed to be contiguous:

... contiguity is in fact part of the vector abstraction. It’s so important, in fact, that when it was discovered that the C++98 standard didn’t completely guarantee contiguity, the C++03 standard was amended to explicitly add the guarantee.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
14

Storage is always contiguous, but it may move as the vector's capacity is changed.

If you had a pointer, reference, or iterator on element zero (or any element) before a capacity-changing operation, it is invalidated and must be reassigned.

Adam Holmberg
  • 7,245
  • 3
  • 30
  • 53
10

Yes it's contiguous

Jasper Bekkers
  • 6,711
  • 32
  • 46
4

std::vector guarantees that the items are stored in a contiguous array, and is therefore the preferred replacement of arrays and can also be used to interface with platform-dependent low-level code (like Win32 API calls). To get a pointer to the array use:

&myVector.front();
Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
Frederik Slijkerman
  • 6,471
  • 28
  • 39
2

yes.

it should alway be contiguous

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156