I'm stuck on how to correct implement date inside a struct that been declared with malloc.
I have these two structs:
typedef struct {
int idWork;
float area;
//char tarifa[MAX_TARIFA_LENG];
int tarifa;
} tWorkspace;
typedef struct{
tPartner *socis;
tWorkspace workP[50];
tContract *contract;
int numSocis;
int numWork;
int numContract;
} tCoworking;
Then, I have this function which I didn't coded right
tCoworking* new_partner(tCoworking *a, int partnerId, char *nam, int descom){
bool exist = false;
a->socis=(tPartner*)malloc(sizeof(tPartner*));
printf("ID %d\n", partnerId);
//CHECK IF PARTNERID EXISTS IN THE LIST
if(a->numSocis != 0){
for(int i=0; i<a->numSocis; i++){
if(a->socis[i].id == partnerId){
exist = true;
printf("\nERROR: Partner %d is already in the list of partners\n",partnerId);
}
}
}
if(exist != true){
//Check if there's no socis
if(a->numSocis != 0){
a->socis[a->numSocis].id = partnerId;
strcpy(a->socis[a->numSocis].name, nam);
a->socis[a->numSocis].descompte = descom;
a->numSocis = a->numSocis+1;
}else{
a->socis[0].id = partnerId;
strcpy(a->socis[0].name, nam);
a->socis[0].descompte = descom;
a->numSocis = 1;
}
}
return a;
}
In main, I have:
tCoworking c;
and this is how I call the function with the data:
new_partner (&c, 11, "Anwar Sherman", 10);
What happens is that when I call it for the first time a->socis[0].id
gives me the ID 11, which is correct.
But when I call it again new_partner (&c, 16, "Isa Warner", 20);
the index 0 lose the previous data and in index 1 writes the data correctly.
I mean, on second call of function, the struct gives me this:
index 0 = 110
index 1 = 16
If I keep calling the function, the previous data is set 0 and the data I pass it "saves"
Why do I use malloc ? I don't know the exact number of users that I will get, so I'm trying to work with Dynamic Memory Allocation and Dynamic Structures
Sorry for bad english and bad explanation, I tried my best.
Thanks.
EDIT
Changed to a->socis=(tPartner*)malloc(sizeof(tPartner))
When I call for the third time my function with different data, it looks like this:
index 0 = 1852989783
index 1 = 0
index 2 = 24
Function calls with data are:
new_partner (&c, 11, "Anwar Sherman", 10);
new_partner (&c, 16, "Isa Warner", 20);
new_partner (&c, 24, "Reagan Sawyer", 8);
More examples:
new_partner (&c, 11, "Anwar Sherman", 10);
new_partner (&c, 16, "Isa Warner", 20);
new_partner (&c, 24, "Reagan Sawyer", 8);
new_partner (&c, 67, "Hashir Lloyd", 10);
What I get:
index 0 = 0
index 1 = 1394634337
index 3 = 0
index 4 = 67