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?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Programmer
  • 8,303
  • 23
  • 78
  • 162
  • 2
    If you simply need an `int *` pointer to pass to a function, you can use `a.data()` – Zpalmtree Nov 15 '18 at 06:49
  • @Programmer - Please refer the updated answer. Earlier there were some wrong information in answer. – Rizwan Nov 15 '18 at 07: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. – StoryTeller - Unslander Monica Nov 15 '18 at 07:33

2 Answers2

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++;
    }
}
Rizwan
  • 3,324
  • 3
  • 17
  • 38
-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.

Rizwan
  • 3,324
  • 3
  • 17
  • 38
Binpord
  • 90
  • 8