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!
Your dealing with pointers is wrong in at least these places:
int
.v->items =(int *) i;
should be
*(v->items) = i;
Your pointer arithmetic is incorrect: subtracting the size and adding an index will get you a pointer prior to the beginning of the allocated area, which is not correct.
You are assigning the results of malloc
to a local variable v
of type "pointer to vector". This assignment has no effect in the caller, because pointers are passed by value. If you wanted to re-assing the vector in the addVector
, you should have taken VectorT **pv
as the first parameter. This code fragment does not look right at all: it appears that you should be assigning v->items=malloc(2 * v->capacity * sizeof(int))
instead of v=malloc(...)
You do not free the old vector when you do a malloc
, causing a memory leak.