This program is supposed to create a dynamic memory vector. I'm pretty sure I'm using malloc correctly. My real problem is some syntax with pointers, particularly a pointer inside a struct.
I'm trying to access the address of an int pointer inside a struct so I can assign it to another pointer
My given struct is:
typedef struct{
int *items;
int capacity;
int size;
}VectorT;
and the function I'm trying to get to work is:
int getVector(VectorT *v, int index){
int *p;
p = v->items;//(2)
p -= v->size;
p += index;
return *p;
}
This is supposed to take the address of the items pointer subtract the number of items in the list and add the index of the desired item to the address of p. Then I return what is at the address of p.
I have a pretty strong feeling that line (2) is not the syntax I need.
Depending on what I've tried so far my program either crashes when getVector is called or it outputs (my best guess) some memory locations.
Here's the code that adds a vector:
void addVector(VectorT *v, int i){
if(v->size >= v->capacity){
//allocate twice as much as old vector and set old pointer to new address
v = (VectorT *) malloc(2 * v->capacity * sizeof(VectorT));
if(v == NULL){
fprintf(stderr, "Memory allocation failed!\n");//error catch
}
else{
v->capacity *= 2;//double the reported capacity variable
v->size++;//add one to the reported size variable
v->items =(int *) i;//add the item to the vector (A)<-----
}
}
else{
v->size++;//add one to the reported size variable
v->items =(int *) i;//add the item to the vector (B)<-----
}
}
I don't feel like my problem is in here, but if it is I have some suspicion at lines A & B...
Any insight would be much appreciated, Thanks!