Array

How do I insert a array size as variable?
Not entirely sure what you mean.

If you're after something along the lines of this:
1
2
int size = 5; //Or any other value
int array[size]; //Error, constant value needed 


Then you just need to use the new[] operator (and delete[] when you've finished with the data)
1
2
3
4
5
int size = 5;
int array* = new int[5];

//Okay, I've finished with this data now, lets free the memory
delete[] array;


Hopefully that answers your question, it's really hard to figure out what you actually mean.
Last edited on
Or a std::vector which is easier than using raw new[] and delete[]:
1
2
3
4
5
6
7
8
9
10
#include <vector>

//...

std::vector<int> my_vector;
my_vector.push_back(23); // my_vector[0] is now 23
my_vector.push_back(32); // my_vector[1] is now 32
my_vector[0] = 2; // my_vector[0] is now 2

// No need to delete[] or anything. Memory will be freed automatically. 
Last edited on
Or even:
1
2
3
4
5
6
7
8
9
10
11
#include <vector>

// ...

int size;
// ... (Get a value for 'size' somehow)
std::vector<int> myVector(size); // Initialize to 'size' elements
// Now use myVector just like an array
myVector[0] = 12;
myVector[3] = 89;
// etc. 
Whats:
myVector[0] = 12;
myVector[3] = 89;

I want the size to be input by the user when it has been debug.
Is that possible?
If you don't know what that does, you should look at your tutorials/course/school docs another time.

1
2
3
4
5
6
7
8
9
10
int a[2];
a[0] = 12;
a[1] = 89;

// is the equivalent of

std::vector<int> b;
b.resize(2);
b[0] = 12;
b[1] = 89;
Last edited on
Topic archived. No new replies allowed.