How to initialize a string into a linked list struct in C -
i have structure player, serves linked list.
i'm trying initialize 'name var' portion of player. i'm receiving error: invalid conversion 'void*' 'char*'.
i don't understand why happening since i've malloc memory , want copy string over.
#include <stdio.h> #include <string.h> #include <stdlib.h> struct player { char *name; int jersey; int points; struct player* next; }; int main() { struct player *head, *ptr; head = (struct player*)malloc(sizeof(struct player)); char playername[] = "hurley"; head->name=malloc(strlen(playername)+1); strncpy(head->name, "hurley"); head->jersey = 11; head->points = 15; head->next = null; ptr = (struct player*)malloc(sizeof(struct player)); char playername2[] = "hill"; ptr->name=malloc(strlen(playername2)+1); strncpy(ptr->name, "hill"); ptr->jersey =33; ptr->points = 17; ptr->next = null; head->next=ptr; printf("head name: %s, next name: %s\n", head->name, ptr->name); free(head); free(ptr); }
the real problem , possible explanation compiling c++ compiler. in c++ there no implicit conversion void *
other pointer types unlike in c there is.
it possible have named file something.cpp causes compiler think c++ code , compile such, leading error mention in post.
other recommendations, are
if going copy given number of bytes have allocated precise ammount of space, this
const char *playername = "hurley"; size_t length = strlen(playername); player->name = malloc(length + 1); if (player->name != null) memcpy(player->name, playername, length + 1);
and better this, can use
strdup()
instead. have checknull
before usingplayer->name
pointer because returnnull
when problem happensmalloc()
too.if writing c code, it's recommended avoid casting
void *
read more information. c programmers might disagree of them think it's better not cast.don't repeat yourself. or known dry principle, in code seems appropriate create function
create_player()
fill instance ofstruct
, repeating code , not good.
Comments
Post a Comment