turning a *pointer elements to an 1D array

Viewed 184

The below c++ code is an example that how we can print the element from a vector.

 #include<iostream> 
#include<iterator> // for iterators 
#include<vector> // for vectors 
using namespace std; 
int main() 
{ 
    vector<int> ar = { 1, 2, 3, 4, 5 }; 

    // Declaring iterator to a vector 
    vector<int>::iterator ptr; 

    // Displaying vector elements using begin() and end() 
    cout << "The vector elements are : "; 
    for (ptr = ar.begin(); ptr < ar.end(); ptr++) 
        cout << *ptr << " "; 

    return 0;     
} 

My question is that how we can transform the element from the ptr*, and make it a 1D array?

the elements of the array will depend on the number of elements i get from *ptr.

for example, my output array would be like this:

int array[i] ={ 1, 2, 3, 4, 5};
3 Answers

You can get a pointer to the data space of the vector using std::vector::data()

int *array = ar.data(); // Notice the pointer notation and please avoid name 'array'

for( int i =0; i < ar.size(); i++) {
   std::cout << array[i] <<'\n';
}

The ptr is a an iterator to vector elements. It simply gives the address where the element is stored in memory. You can read the value stored in the memory by dereferencing it i.e. *ptr.

enter image description here

If you want to create array out of your vector, you need to know the size of array at compile time, but you can use dynamiclly allocated memory instead here is an example:

int* arr = new int [vec.size()];
for(int i = 0; i < vec.size(); ++i)
{
    arr[i] = vec[i];
}

delete [] arr;
Related