Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can i declare an array while the program is running?
Something like :

C++
std::cin>> l ;
int array[l] ;


It doesn't work, it gets an Intelisence Err,

Expression must have an instance value.

I'm using visual studio 2010.

Thank you,
Posted
Updated 25-Apr-13 5:47am
v2

An alternative to using new and delete is to use the STL (standard template library) vector class - then you don't need to worry about deallocating since the vector class handles it.
E.g.
C++
#include <vector>

void foo()
{
    std::cin >> len;
    std::vector<int> a(len);
    // use the array "a"...
}



Regards,
Ian.
 
Share this answer
 
v3
Comments
H.Brydon 25-Apr-13 12:14pm    
Right on both counts. Thanks for the update on my answer.
Ian A Davidson 25-Apr-13 17:01pm    
Any time.
Ian.
nv3 25-Apr-13 12:21pm    
Good idea to use std::vector, although most beginners are overwhelmed with STL's complexity. Just as a comment: "array" is no C++ keyword, just a data type used in C++/CLI. But I agree, it would not be a good idea to give that name to a program variable.
Ian A Davidson 25-Apr-13 16:59pm    
Good point. I was wondering about it - I just noticed that the encoding on this page turned it blue and looked it up here: http://msdn.microsoft.com/en-GB/library/2e6a4at9(v=vs.80).aspx I didn't spot that it was just a CLI thing.
Personally I've not done C++ with the CLI (what's the point when it is so different from proper C++, and if you want to use the CLR, C# is so much nicer).
But still, even if you're doing proper C++ in Visual Studio it's probably best to avoid it. Besides, as you indicate, one should use variables which indicate what they are for, rather than what type they are.
Regards,
Ian.
Espen Harlinn 25-Apr-13 18:42pm    
5'ed!
Something like this:

C++
void foo()
{
    std::cin >> len;
    int* a = new int[len];  // "array" is a reserved keyword in VC++ as it is used in C++/CLI.
    // use the array "a"...
    delete [] a;  // after allocating with new[] you must use delete[] - the square brackets are important.
}
 
Share this answer
 
v4
Comments
m.r.m.40 25-Apr-13 11:58am    
It worked.
thank you,
Espen Harlinn 25-Apr-13 18:39pm    
5'ed!
H.Brydon 25-Apr-13 20:45pm    
Thanks again!
Espen Harlinn 25-Apr-13 20:46pm    
You're wellcome :-D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900