Reputation: 225
vector_dinamic *creeaza_vector()
{
vector_dinamic *v=malloc(sizeof(vector_dinamic)*capacitate_initiala);
v->Element=malloc(sizeof(Elements)*capacitate_initiala);
v->lungimea=0;
v->capacitatea=capacitate_initiala;
return v;
}
This is a dynamic vector where lungimea is the length and capacitatea is the capacity. capcacitatea_initiala is 100, which means i can store 100 elements.
typedef void* Elements;
typedef struct{
Elements * Element;
int lungimea;
int capacitatea;
} vector_dinamic;
I also have this type void of elements, to be able to store elements of different types in my vector , I've managed to do the add, but my question is how can I compare two elements of the same type , i want to implement the delete function but I'm struggling to compare two elements
typedef struct{
int numar_apartament;
int suma;
char * tipul;
} Cheltuieli;
I have this element type , now could somebody tell me how to compare the elements in my generic vector by the "numar_apartament"?
void modifica(vector_dinamic * vector, int numar_apartament)
{
int i,a=0;
for (i=0;i<vector->lungimea;i++)
{
if (vector->Element[i]->numar_apartament)==element->numar_apartament)
a=1;
}
return a;
}
This is what i tried but I get a lot of errors and it does not work ...
Thank you!
Upvotes: 0
Views: 499
Reputation: 100
The main idea is to take the pointers to the variables that you want to compare and use memcmp to compare. Also corrected some compilation errors and below is the modified code. Check if it helps!
#include "malloc.h"
#include "memory.h"
typedef void* Elements;
typedef struct{
Elements * Element;
int lungimea;
int capacitatea;
} vector_dinamic;
typedef struct{
int numar_apartament;
int suma;
char * tipul;
} Cheltuieli;
vector_dinamic *creeaza_vector()
{
int capacitate_initiala = 10;
vector_dinamic *v = (vector_dinamic *)malloc(sizeof(vector_dinamic)*capacitate_initiala);
v->Element= (Elements *)malloc(sizeof(Elements)*capacitate_initiala);
v->lungimea = 0;
v->capacitatea = capacitate_initiala;
return v;
}
int modifica(vector_dinamic *vector, int numar_apartament)
{
int i, a = 0;
Cheltuieli **tmp = (Cheltuieli **)&(vector->Element);
for (i = 0; i < vector->lungimea; i++)
{
if ((memcmp(&(tmp[i])->numar_apartament, &numar_apartament, sizeof(int)) == 0))
a = 1;
}
return a;
}
Upvotes: 1
Reputation: 409136
void
pointers don't have any specific type, which is why they can point to anything. You have to cast void
pointers to the actual type they point to, to be able to dereference them:
((Cheltuieli *) vector->Element[i])->numar_apartament
You also have problems with the parentheses, you're missing an opening parentheses.
Upvotes: 3