Skip to content
Related Articles

Related Articles

array data() in C++ STL with Examples
  • Last Updated : 23 Jul, 2018

The array::data() is a built-in function in C++ STL which returns an pointer pointing to the first element in the array object.

Syntax:

array_name.data()

Parameters: The function does not accept any parameters.

Return Value: The function returns an pointer.

Below programs illustrate the above function:



Program 1:




// CPP program to demonstrate the
// array::data() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    array<int, 5> arr = { 1, 2, 3, 4, 5 };
  
    // prints the array elements
    cout << "The array elements are: ";
    for (auto it = arr.begin(); it != arr.end(); it++)
        cout << *it << " ";
  
    // Points to the first element
    auto it = arr.data();
  
    cout << "\nThe first element is:" << *it;
  
    return 0;
}
Output:
The array elements are: 1 2 3 4 5 
The first element is:1

Program 2:




// CPP program to demonstrate the
// array::data() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    array<int, 5> arr = { 1, 2, 3, 4, 5 };
  
    // prints the array elements
    cout << "The array elements are: ";
    for (auto it = arr.begin(); it != arr.end(); it++)
        cout << *it << " ";
  
    // Points to the first element
    auto it = arr.data();
  
    // increment
    it++;
    cout << "\nThe second element is: " << *it;
  
    // increment
    it++;
    cout << "\nThe third element is: " << *it;
  
    return 0;
}
Output:
The array elements are: 1 2 3 4 5 
The second element is: 2
The third element is: 3
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :