Re: Array size
Pavan wrote:
On Feb 18, 6:18 pm, Michael DOUBEZ <michael.dou...@free.fr> wrote:
Tim Love a ?crit :
Pavan <pavan...@gmail.com> writes:
...
First of all is it safe to do like that?
First of all, check that it's legal ANSI C++. No doubt it will be
one day, but is it yet?
It is valid C99 and it is true that now, most c++ compiler will
accept this code unless you specific strict compilation options
(std=c89).
int n = 0;
cin >> n;
int arr[n];
Suppose when we run this application, we enter value of n as 10,
then does it create an array for 10 integers or does it create
only for 0?
It does create a array of 10 elements. It is called VLA (Variable
Length Array).
First of all is it safe to do like that?
I don't know; what happens if n<0 ? I guess C is silent about this
case.
Do you really need it ? I guess not.
Why don't you use a plain vector ?
Michael
I didnt need exactly that kind of scenario.
But what I need is I have a function like this
bool f(std::vector vec)
{
int arr[vec.size()];
......
......
.....
}
In the above I have a function that will create a array based on the
size of vector argument passed
to it. So I wanted to know is it ok to do like that. Also is it
allowed in VC++(windows) also?
As stated, it is not currently a part of the C++ standard. But my question
is why? Why do you want to create a variable lenght array as shown when you
can use a vector? What is wrong with:
std::vector<int> arr( vec.size() );
How does that not serve your purpose?
You can use that anywhere you can use an array of int although you need to
go an extra step when getting a pointer to the first element. With the
array you would use
arr
with the vector it would be
&arr[0]
&arr[0] should be an int* which should be usable where you would need either
an int * or int []
--
Jim Langston
tazmaster@rocketmail.com