In C programming language I have to write a program using Vector Abstract Data T
ID: 664175 • Letter: I
Question
In C programming language I have to write a program using Vector Abstract Data Type. I have a node.h and a node.c files and I also have a vector.h and have to create a vector.c file. I have almost everything done except for a void vadd(VectorT *vector, NodeItemT item) function. I am suppose to use this function to append a new element to the end of the vector. If the capacity of the vector is reached, the vector is supposed to dynamically grow by a fixed rate. *this is all supposed to happen in side the void vadd(VectorT *vector, NodeItemT item) function. images of my node.h and node.c and vector.h files are below.
node.c ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
vector.c vadd function above is what I have so far but I am getting a segmentation fault, like my vector is not dynamically growing. anyhelp would be greatly appreciated.
Explanation / Answer
the segmentation fault is coming because you haven't allocated the memory for this function.
use malloc to allocate the memory first when you are growing the size of the vector.
void add1(VectorT *vector, NodeItemT item)
{
NodeT *tempList;
int i;
if((vector->size)>=(vector->capacity))
{
tempList=(NodeT*)malloc(((vector->capacity)*2)*sizeof(NodeT*));
for(i=0;i<vector->capacity;i++)
tempList[i]=vector->list[i];
for(i=vector->capacity;i<((vector->capacity)*2);i++);
tempList[i].info='';
vector->list=tempList;
vector->capacity=((vector->capacity)*2);
}
vector->list[vector->size].info=item;
vector->size=(vector->size)+1;
}