0

I have declared a array of int in c++ with some size. say, int a[6]

at runtime if my array size exceeds 6, then i need to increase it.

i am not going to use pointer, vector and the size will not be given by the user.

5
  • 5
    do you have any good reason not to use a std::vector? If not, use it! Commented Mar 19, 2015 at 12:13
  • 2
    Possible duplicate of stackoverflow.com/questions/756906/… Commented Mar 19, 2015 at 12:14
  • Why malloc/calloc in C++? New is the order of the day Commented Mar 19, 2015 at 12:25
  • 1
    I don't normally say this but I'd recommend asking this question of either C or C++ (or asking two questions). The two languages are so divergent in this area that you might as well tag this C and Java for all the overlap you'll get. Commented Mar 19, 2015 at 12:39
  • This is not a duplicate of anything and not a unclear one. If you dont know the answer dont close it, ask your doubt and get clarified. Commented Jan 25, 2016 at 12:22

2 Answers 2

4

C arrays are statically resolved at compile-time therefore can't be resized at runtime.

If you don't want to use std::vector, malloc or new, there is another option: declare a "big-enough" array and then hold the number of used elements in another variable. E.g.:

int a[big_enough];
size_t a_size = 0;

But my advice is definitely to use std::vector! E.g.:

std::vector<int> a(6);

initialize a vector of 6 ints equal to 0.

If you need to change their value, you can access them with

a[i] = 3;

where i is an integer between 0 and 5 (that is a.size()).

By the way, often you dont't want to explicitly set the vector size. Declare it empty and then add elements one by one. E.g:

std::vector<int> a;
a.push_back(-3);
Sign up to request clarification or add additional context in comments.

6 Comments

I am not sure that "C arrays can't be resized at runtime." is correct. You can delete(free) array and then create new(malloc). std::vector works like this. But in std::vector you can forget about working directly with memory, because this class does if for you
hey, i know i can use vector. is there any other way apart from vector??
@Praveenkumar:- Check my answer. Thats the alternative way of doing it.
@Praveenkumar I've updated my answer. Hope it's useful.
@MikeMinaev Arrays and memory allocated with malloc are different exactly in that: arrays are static memory reserved on the stack, malloc allocates at runtime dynamic memory on the free store.
|
1

You can not change the size of your array at run time. An alternative is to create a new array which is larger than the existing one. Copy the elements of the existing array to the new array and delete the existing array. And Change the member variables, ptr and size.

Something like this:

int* newArray = new int[sizeOfArray];
std::copy(oldArray, oldArray + std::min(sizeofOldArray, sizeOfArray), newArray);
delete[] oldArray;
oldArray = newArray;

The best is to use the std::vector

Comments