In C++, std::array::data() returns a pointer to the memory where the array keeps its elements. The pointer points to the first element, and all elements sit one after another after it.
This is handy when you must call older C-style code that wants a plain int* and a length. Include <array> to use it.
This is a member of std::array<T, N>, not of a plain C array and not of std::vector. A std::array has a fixed size N that is part of its type, and it lives on the stack like a normal variable.
Syntax
Call data with empty brackets. It takes no arguments.
C++
int* p = nums.data();
const int* q = cnums.data();
Call
What it does
nums.data()
Returns a pointer to the first element. You can read and write through it.
nums.data()[2]
Reads the element at index 2 through the pointer.
The pointer is only valid while the array exists. Do not keep it after the array goes out of scope.
p points into the memory owned by a, not to a copy.
p[2] = 99 changes the third element, so a[2] now shows 99.
data() equals &a[0], because both are the address of the first element.
Frequently Asked Questions
It returns a pointer to the first element of the array. The elements are stored one after another, so you can reach the others with p[1], p[2], and so on.
Use it when you call C-style code that wants a pointer and a length. For normal C++ code, at(), [] and iterators are safer.
No. data() returns a plain pointer (T*). begin() returns an iterator. For std::array they point to the same spot, but they are different types.
No. Always pass size() together with it so the other code knows where the array stops.
The pointer becomes invalid (a dangling pointer). Do not use it after the array goes out of scope.