I already get how to add an int to a linked list in C but I need to add a string and it simply doesn't work.
The main function gets the data from the user and prints it in the show function after adding it to the linked list.
list and main
struct nlista{
char dado[10];
struct nlista *prox;
}*Head;
int main(){
int op;
char data[10];
Head = NULL;
printf("type a value: ");
scanf("%s",&data);
inserir(data);
printf("the element is : ");
show();
}
inserir(): add the element in the end of list
void inserir(char data){
nlista *novoelemento;
novoelemento = (struct nlista *)malloc(sizeof(struct nlista));
nlista *check;
check = (struct nlista *)malloc(sizeof(struct nlista));
novoelemento->dado = data;
if(Head == NULL){
Head = novoelemento;
Head->prox = NULL;
}
else{
check = Head;
while(check->prox != NULL)
check = check->prox;
check->prox = novoelemento;
novoelemento->prox = NULL;
}
show(): display the linked list
void show()
{
nlista *check;
check = (struct nlista *)malloc(sizeof(struct nlista));
check = Head;
if (check == NULL){
return;
}
while(check != NULL) {
printf("%s", check->dado);
check=check->prox;
}
printf("\n");
}
What am I missing? The compiler message is: invalid conversion from char* to char. in the line of inserir(data);
check = (struct nlista *)malloc(sizeof(struct nlista));? What purpose does that newly created element serve? And ifinseriris supposed to add a string, why does it take a character parameter? It would help to have comments explaining why the code is written as it is.datadecays to a pointer (char *) butvoid inserir(char data)is asking for acharchar*.