I would like to be able to convert between std::vector and its underlying C array int* without explicitly copying the data.

Does std::vector provide access to the underlying C array? I am looking for something like this

```
vector<int> v (4,100)
int* pv = v.c_array();
```

EDIT:

Also, is it possible to do the converse, i.e. how would I initialize an `std::vector`

from a C array without copying?

```
int pv[4] = { 4, 4, 4, 4};
vector<int> v (pv);
```

You can get a pointer to the first element as follows:

```
int* pv = &v[0];
```

This pointer is only valid as long as the vector is not reallocated. Reallocation happens automatically if you insert more elements than will fit in the vector's remaining capacity (that is, if `v.size() + NumberOfNewElements > v.capacity()`

. You can use `v.reserve(NewCapacity)`

to ensure the vector has a capacity of at least `NewCapacity`

.

Also remember that when the vector gets destroyed, the underlying array gets deleted as well.

Licensed under: CC-BY-SA with attribution

Not affiliated with: Stack Overflow