1

VC++ is giving an error on below code:

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> a;
    a.push_back(10);
    a.push_back(20);
    a.push_back(30);
    int arr[a.size()];
    std::copy(a.begin(), a.end(), arr);
    for(int index = 0 ; index < a.size(); index++)
    {
        std::cout << " The value is " << arr[index] << std::endl;
    }
}

It errors out at the integer array declaration stating that the value of variable 'a' cannot be used as constant?

How can we resolve the issue where my objective is to transfer content of vector into a 'C' style array?

3
  • 2
    If you simply need an int * pointer to pass to a function, you can use a.data() Commented Nov 15, 2018 at 6:49
  • @Programmer - Please refer the updated answer. Earlier there were some wrong information in answer. Commented Nov 15, 2018 at 7:33
  • 1
    I may be naive for asking, but honestly, why do that? auto copy_a = a; will get you the very same thing, without any hassle, headaches or having to worry about the need to manually delete[] anything. Commented Nov 15, 2018 at 7:33

2 Answers 2

3

This error is compiler dependent. C++ demands constants in array definitions. Some compilers offer an extension that help to use non-constants while declaring Array. I successfully compiled your code on Xcode 10 (GCC).

For your compiler you can simply add int *arrPtr = a.data(); to get c-style array pointer for given array.

int main()
{
    std::vector<int> a;
    a.push_back(10);
    a.push_back(20);
    a.push_back(30);
    //int arr[a.size()];
    //std::copy(a.begin(), a.end(), arr);
    //for(int index = 0 ; index < a.size(); index++)
    //{
    //    std::cout << " The value is " << arr[index] << std::endl;
    //}

    int *arrPtr = a.data();
    for(int index = 0 ; index < a.size(); index++)
        std::cout<< " The value is " << arrPtr[index] << std::endl;

    for(int index = 0 ; index < a.size(); index++)
    {
        std::cout<< " The value is " << *arrPtr << std::endl;
        arrPtr++;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

"Some compilers need constants while declaring Array" - No, the C++ language demands constants in array definitions. Some compilers just offer an extension that is beyond C++.
@StoryTeller - thanks for explaining. Updated answer accordingly.
-2

What compiler tells you, is that a.size() is not a compile time constant ?. Hence, you cannot declare array like this. You need to call int *arr = new int[a.size()]; and then delete it later.

1 Comment

No, the OP most certainly doesn't need to burden themselves with manually managing array lifetimes. Copying a vector to another vector is a one liner, and correct by construction.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.