1

I have an array inside a class which is:

private:
    static const int MAX_EQUIPS=100;
    equip a_t[MAX_EQUIPS];
    int a_n;

Then in the main they tell me what MAX_EQUIPS size should be, how can I put it so it changes? It starts at X but then it increases or decreases when the new valor is entered.

3
  • 1
    If it changes, it isn't const, is it? Use a vector. Commented Mar 16, 2013 at 12:23
  • 1
    I do not think the OP means the length of the array changes at runtime, but rather that in main() somehow he gets a value and that value dictates the size of the array Commented Mar 16, 2013 at 12:26
  • @stijn exactly, I need to put a size before running it but then when they tell me what size it actually is I need to change it Commented Mar 16, 2013 at 12:48

3 Answers 3

1

It seems you are referring to variable length arrays which are not permitted in C++. many possible alternatives exist, for instance you can use a vector

Sign up to request clarification or add additional context in comments.

Comments

1

A c++ solution would be:

class MyClass
{
public:
  MyClass( size_t n ) :
    a_t( n )
  {
  }

private:
  std::vector< int > a_t;
};

3 Comments

I've tried this and either I don't know how to adapt it to my code or it doesn't work. When I do it it keeps saying MAX_EQUIPS isn't declared and I can't use the vector anymore in the same class
Please post an update with the code you're trying to use then - the example above should wor, and basic vector access semantics are like array semantics, that is you can use a_t[ 0 ] etc.
Oops sry, I finished it last night and I didn't remember to post it. I didn't change the array size in the end, I created a new variable that I used for a different array size and worked with that
1

I would suggest using std::vector for this, as it will wrap most of this itself.

private:
    std::vector<int> a_t;

Then when you're given the size: a_t.resize(MAX_EQUIPS);

Your a_n will be a_t.size().

However, if you Really want to do it yourself, you'll need to do some allocation (which you should tie to ctor/dtor semantics.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.