Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define array, then change its size

Tags:

c++

arrays

I come from a java background and there's something I could do in Java that I need to do in C++, but I'm not sure how to do it.

I need to declare an array, but at the moment I don't know the size. Once I know the size, then I set the size of the array. I java I would just do something like:

int [] array;

then

array = new int[someSize];

How do I do this in C++?

like image 729
user69514 Avatar asked Oct 03 '10 19:10

user69514


4 Answers

you want to use std::vector in most cases.

std::vector<int> array;

array.resize(someSize);

But if you insist on using new, then you have do to a bit more work than you do in Java.

int *array;
array = new int[someSize];

// then, later when you're done with array

delete [] array;

No c++ runtimes come with garbage collection by default, so the delete[] is required to avoid leaking memory. You can get the best of both worlds using a smart pointer type, but really, just use std::vector.

like image 192
SingleNegationElimination Avatar answered Sep 21 '22 17:09

SingleNegationElimination


In C++ you can do:

int *array; // declare a pointer of type int.
array = new int[someSize]; // dynamically allocate memory using new

and once you are done using the memory..de-allocate it using delete as:

delete[]array;
like image 35
codaddict Avatar answered Sep 20 '22 17:09

codaddict


Best way would be for you to use a std::vector. It does all you want and is easy to use and learn. Also, since this is C++, you should use a vector instead of an array. Here is an excellent reason as to why you should use a container class (a vector) instead of an array.

Vectors are dynamic in size and grow as you need them - just what you want.

like image 44
user225312 Avatar answered Sep 20 '22 17:09

user225312


The exact answer:

char * array = new char[64]; // 64-byte array

// New array
delete[] array;
array = new char[64];

std::vector is a much better choice in most cases, however. It does what you need without the manual delete and new commands.

like image 42
ssube Avatar answered Sep 23 '22 17:09

ssube