C++ <array> - data() Function
The C++ array::data function is used to create a pointer to the first element of the array. The retrieved pointer can be offset to access any element of the array.
Syntax
value_type* data() noexcept; const value_type* data() const noexcept;
Parameters
No parameter is required.
Return Value
A pointer to the first element of the array.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the array::data function is used to create a pointer pointing to the first element of the array MyArray. It is further used to alter other elements of the array.
#include <iostream> #include <array> using namespace std; int main (){ array<int, 5> MyArray{10, 20, 30, 40, 50}; int* p = MyArray.data(); cout<<"First element is: "<<*p<<"\n"; p++; cout<<"Second element is: "<<*p<<"\n"; *p = 100; cout<<"Now the second element is: "<<*p<<"\n"; p[3] = p[3] + 500; cout<<"Now the fifth element is: "<<p[3]<<"\n"; return 0; }
The output of the above code will be:
First element is: 10 Second element is: 20 Now the second element is: 100 Now the fifth element is: 550
❮ C++ <array> Library