This line seems to be wrong:
getNode(playerList, n)->data = &player;
player
is already a pointer to a Player
, thus, this line is actually setting the new node's data
field to a pointer to pointer to Player
, and the rest of your code uses it as if it were a pointer to Player
- type mismatch, that's your problem.
Instead, that line should be:
getNode(playerList, n)->data = player;
That is, you do not need to apply the address of operator. The rest of the code looks ok.
The code seems to be fine because your printing statements are misleading. You only allocate one node, and keep changing its value over and over. The thing is, for each time you change the fields on that node, you print it, so the output looks correct, but the program is only ever storing one node with one piece of information at a time. You store, print it, overwrite, print, overwrite, print....
To fix this, you need to explicitly allocate a new node on each iteration:
Player *player;
int n;
for(n = 0; n < i; n++) {
if(vals[n][0] != NULL) {
player = calloc(1, sizeof(Player));
addNode(playerList, n, NULL);
getNode(playerList, n)->data = player;
((Player *)getNode(playerList, n)->data)->name = vals[n][0];
((Player *)getNode(playerList, n)->data)->pos = vals[n][1];
((Player *)getNode(playerList, n)->data)->num = vals[n][2];
}
}
And then, after populating the list, print it:
for(n = 0; n < i; n++) {
if(vals[n][0] != NULL) {
printf("%d: %s\n", n, ((Player *)getNode(playerList, n)->data)->name);
printf("%d: %s\n", n, ((Player *)getNode(playerList, n)->data)->pos);
printf("%d: %s\n", n, ((Player *)getNode(playerList, n)->data)->num);
printf("\n");
}
}
Also, if you don't want to copy the pointers from the array but duplicate its contents, you can use strdup()
:
/* ... */
((Player *)getNode(playerList, n)->data)->name = strdup(vals[n][0]);
((Player *)getNode(playerList, n)->data)->pos = strdup(vals[n][1]);
However, remember that you must now free()
each one of name
and pos
before freeing the node itself. Also, since num
is a pointer to double, you can't use strdup
on it. Instead, you must manually allocate memory and copy its contents:
((Player *)getNode(playerList, n)->data)->num = malloc(sizeof(double));
*((Player *)getNode(playerList, n)->data)->num = *vals[n][2];