i know i learned it somewhere, but its been a while since i used it... how do you make an user given array size... i mean...

int b;
cout<<"Input the array size: ";
cin>>b;
int array[b];

i know this is not hte way of doing it... but just so you get the idea of what i need to do...

Recommended Answers

All 6 Replies

int *array = new int[b]; Or if you can, use a std::vector

i know i learned it somewhere, but its been a while since i used it... how do you make an user given array size... i mean...

int b;
cout<<"Input the array size: ";
cin>>b;
int array[b];

i know this is not hte way of doing it... but just so you get the idea of what i need to do...

arrays have to be constant
maybe:
const int size = b;
int array;
Of coarse, once it's done, you can't re-size it.

why not use a vector?

arrays have to be constant
maybe:
const int size = b;
int array;
Of coarse, once it's done, you can't re-size it.

why not use a vector?

did you try it? 'cuz when i did that, it sent me the error Error 13: Constant expression required i don't use a vector because it is not what i need...

thnx for your help...

did you try it? 'cuz when i did that, it sent me the error Error 13: Constant expression required i don't use a vector because it is not what i need...

I just looked it up. Arrays cannot be intialized with a non-const value or a value unknown at compile time. That's why it failed.
You will have to initailize it with the largest possible size required.
Perhaps use a pointer with a limlit set in a loop by a user determined variable might be the way to go?

I don't know WHY you need to do thsi, so it's hard to guess what other methods might be appropriate.

Good luck!

I don't know WHY you need to do thsi, so it's hard to guess what other methods might be appropriate.

For a statically allocated array, the size must be known at compile time - therefore there's no reason to allow a non-const variable to be used to declare an array.

Allowing such behaviour inevitably invites beginners to try such things as the following, which, if it weren't illegal, would be undefined behaviour

int main()
{
    int size(5);
    int arr[size] = { 1,2,3,4,5 };
    size = 8;
    arr[5] = 6;
}

Disallowing non-const variables to be used in static array declarations adds a compile-time check to help prevent this kind of code appearing.

There may be other reasons the ISO standards committee decided to disallow it, but this seems reason enough to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.