array data() in C++ STL with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

The array elements are: 1 2 3 4 5 
The first element is:1

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

The array elements are: 1 2 3 4 5 
The second element is: 2
The third element is: 3


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.