Increase array size at runtime in c++ without vector, pointer [closed]

不问归期 提交于 2020-01-17 08:16:44

问题


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.


回答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




回答2:


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);


来源:https://stackoverflow.com/questions/29144255/increase-array-size-at-runtime-in-c-without-vector-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!