I have a structure containing pointers that I would like to populate from an array, both defined below. I'm using strtok to split a string in the elements
array and then take the individual values and put them in the relevant structure values.
I can split the string ok but the value that is populated into eleNum
is wrong. I appear to be getting a pointer value or something similar. I'm also unsure if my memory allocations for the 3 fields (eleNum, eleSym, eleName
) are correct. They work for eleSym
and eleName
but I don't know if this is just luck or the right way of mallocing space for them.
typedef struct PTdef {
int *eleNum;
char *eleSym;
char *eleName;
} ptDB;
int main(void)
{
ptDB pt[118] = {};
char elements[][40] = {"1,H,Hydrogen"};
char *token;
char *eleDup = (char *)malloc(40);
char sep[] = ",";
strcpy(eleDup, elements[0]);
token = strtok(eleDup, sep);
pt[0].eleNum = malloc(sizeof(int));
pt[0].eleSym = (char *)malloc(sizeof(token));
pt[0].eleName = (char *)malloc(strlen(token));
pt[0].eleNum = (int *)token;
token = strtok(NULL, sep);
strcpy(pt[0].eleSym, token);
token = strtok(NULL, sep);
strcpy(pt[0].eleName, token);
Output should be.
pt[0].eleNum = 1.
pt[0].eleSym = H.
pt[0].eleName = Hydrogen.