I’m working on an assignment right now where we create our own basic, dynamically allocated vector struct. One of the functions we are supposed to make is a function to extend the vector when the user enters values.
struct Vector{//vector structure
unsigned int size;
Elem *svector;
};
Vector *extend_vec(Vector *extend,Elem element){
if (extend==NULL){
return NULL;}
Elem *tempVec=new Elem[(*extend).size];
memcpy(tempVec,(*extend).svector,sizeof((*extend).svector));//copies memory from the original array to the temp array
(*extend).size+=1;
delete[] (*extend).svector;//clears the memory
(*extend).svector=new Elem[(*extend).size];//reallocates with the new size
}
Elem=float btw**
My question is whether this line is necessary, and why :
delete[] (*extend).svector;//clears the memory
I’m a bit hazy on how memory is overwritten/reallocated in a situation like this. I’m not sure if reallocating overwrites whats already there.
**So I read through everyone’s comments and this is what I came up with.
Vector *extend_vec(Vector *extend,Elem element){
if (extend==NULL){
return NULL;}
Elem *tempVec=new Elem[extend->size+1];
tempVec[extend->size+1]=element;
memcpy(tempVec,extend->svector,(extend->size*sizeof(Elem)));//copies the memory from the original array to the rest of the temp array
extend->size+=1;
delete[] extend->svector;//clears the memory
extend->svector=tempVec;//the original vector now becomes the extended vector
delete[] tempVec;//clears the temporary memory
return extend;
}
I don’t think the code presented here will work as expected. I think what you want is: