Reputation: 11
I want to initialize a struct using a function and also insert into it as seen below. I want to initialize the array dynamically I want to declare two struct vectors, one dynamically and the other statically
Upvotes: 0
Views: 193
Reputation: 595412
Your initialize()
function is not allocating any memory for the array, and it is also not initializing the current_size
to the correct value. It needs to look like this instead:
void initialize(vector &vec, int size){
vec.current_size = 0;
vec.array = new int[size];
vec.max_size = size;
}
And then you need a function to free the array when you are done using it, eg:
void finalize(vector &vec){
delete[] vec.array;
vec.current_size = 0;
vec.max_size = 0;
}
Also, your insert()
function should be updated to avoid a buffer overflow once the array fills up to its max capacity:
void insert( vector &vec, int element){
if (vec.current_size < vec.max_size){
vec.array[vec.current_size] = element;
vec.current_size++;
}
}
If needed, this would also allow you to grow the array instead:
void insert( vector &vec, int element){
if (vec.current_size == vec.max_size){
int new_max = vec.max_size * 2;
int *new_array = new int[new_max];
for(int i = 0; i < vec.current_size; ++i){
new_array[i] = vec.array[i];
}
delete[] vec.array;
vec.array = new_array;
vec.max_size = new_max;
}
vec.array[vec.current_size] = element;
vec.current_size++;
}
Upvotes: 2