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 compiler. in there no implicit conversion void * other pointer types unlike in there is.

it possible have named file something.cpp causes compiler think code , compile such, leading error mention in post.

other recommendations, are

  1. 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 check null before using player->name pointer because return null when problem happens malloc() too.

  2. if writing code, it's recommended avoid casting void * read more information. programmers might disagree of them think it's better not cast.

  3. don't repeat yourself. or known dry principle, in code seems appropriate create function create_player() fill instance of struct, repeating code , not good.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -