Convert std::vector to C-style Array

Convert std::vector to C-style Array

When working with C++ codebases, you may encounter situations where you need to interface with legacy C libraries or functions that expect traditional C-style arrays instead of the more convenient std::vector. This tutorial explains how to convert std::vector to C-style array.

Use data function to convert std::vector to C-style array. It obtains a pointer to the first element in the array, which is internally used by the vector. Any modifications made to the elements of a C-style array will reflect in the vector itself, as they essentially operate on the same data.

#include <iostream>
#include <vector>

int main()
{
    std::vector arr = {1, 10, 100};
    int *carr = arr.data();

    for (int i = 0; i < arr.size(); ++i) {
        std::cout << carr[i] << std::endl;
    }

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.