C++ std::array::data

The std::array::data function returns a pointer to the first element of the array. This allows direct access to the underlying array, enabling integration with C-style array functions or APIs that require raw pointers.

This function provides a safe and standard way to retrieve the data pointer from a std::array.


Syntax of std::array::data

</>
Copy
pointer data() noexcept;
const_pointer data() const noexcept;

Parameters

The std::array::data function does not take any parameters.

Return Value

Returns a pointer to the first element of the array. If the array is const, the returned pointer is also const.

Exceptions

The std::array::data function does not throw exceptions as it is marked noexcept.


Examples for std::array::data

Example 1: Accessing Elements Using std::array::data

This example demonstrates how to use the data function to access elements of a std::array:

</>
Copy
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> arr = {10, 20, 30, 40, 50};

    int* ptr = arr.data(); // Get the pointer to the first element

    std::cout << "Elements in the array: ";
    for (std::size_t i = 0; i < arr.size(); ++i) {
        std::cout << *(ptr + i) << " "; // Access elements using the pointer
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. A std::array named arr is initialized with elements {10, 20, 30, 40, 50}.
  2. The data() function returns a pointer to the first element of the array and assigns it to ptr.
  3. A for loop iterates through the array, accessing elements using pointer arithmetic (*(ptr + i)).
  4. The program outputs all the elements in the array.

Output:

Elements in the array: 10 20 30 40 50

Example 2: Using std::array::data with a C-style Function

This example demonstrates passing a std::array to a C-style function using the pointer returned by data():

</>
Copy
#include <iostream>
#include <array>

void printArray(const int* arr, std::size_t size) {
    for (std::size_t i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};

    std::cout << "Array elements: ";
    printArray(arr.data(), arr.size()); // Pass the pointer and size to the function

    return 0;
}

Explanation:

  1. A std::array named arr is initialized with elements {1, 2, 3, 4, 5}.
  2. The data() function is used to get a pointer to the first element of the array.
  3. The printArray function is called with the pointer returned by data() and the size of the array.
  4. The printArray function iterates through the array using the pointer and prints all the elements.

Output:

Array elements: 1 2 3 4 5