i have problem with assigning an array as an element of a linked list. I've tried changing char to char* but it didn't help me. I would really appreciate your name here i created a struct
struct node{
char data;
struct node *next;
};
and added this function to add new nodes
void addLast(struct node **head, char val)
{
//create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
//if head is NULL, it is an empty list
if(*head == NULL)
*head = newNode;
//Otherwise, find the last node and add the newNode
else
{
struct node *lastNode = *head;
//last node's next address will be NULL.
while(lastNode->next != NULL)
{
lastNode = lastNode->next;
}
//add the newNode at the end of the linked list
lastNode->next = newNode;
}
}
and this is how to pass the data to function
int main()
{
struct node *head = NULL;
char name[10];
printf("Enter book title : ");
scanf("%s",&name);
addLast(&head,name);
break;
return 0;
}
and this is the error i get
error: invalid conversion from 'char*' to 'char' [-fpermissive]
| addLast(&head,name);
| ^~~~
| |
| char*
note: initializing argument 2 of 'void addLast(node**, char)'
void addLast(struct node **head, char val)
Just redeclare the structure like
#include <strio.h>
#include <stdlib.h>
#include <string.h>
//...
#define NAME_LENGTH 10
struct node{
char name[NAME_LENGTH];
struct node *next;
};
In this case the function will look like
int addLast( struct node **head, const char *name )
{
//create a new node
struct node *newNode = malloc( sizeof( struct node ) );
int success = newNode != NULL;
if ( success )
{
strncpy( newNode->name, name, NAME_LENGTH );
newNode->name[NAME_LENGTH - 1] = '\0';
newNode->next = NULL;
//if head is NULL, it is an empty list
if ( *head == NULL )
{
*head = newNode;
}
//Otherwise, find the last node and add the newNode
else
{
struct node *lastNode = *head;
//last node's next address will be NULL.
while ( lastNode->next != NULL )
{
lastNode = lastNode->next;
}
//add the newNode at the end of the linked list
lastNode->next = newNode;
}
}
return success;
}