Click here to Skip to main content
15,741,981 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to create a linked list using a void* to store a word in each node. I am not sure at which point to typecast the data, and i continue to get the error:

linked_list_generic.c:63:10: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘void *’ [-Werror=format=]
printf("%s ", temp->data);

I am new to generic linked lists so any help would be great.

What I have tried:

<pre>#include <stdio.h>
#include <stdlib.h>

/*Typedef declarations*/

typedef struct Node
{
	void* data;
	struct Node* next;
}Node;

typedef struct 
{
	Node* head;
}Linked_List;

/*------------------------------------------------------------------*/

Linked_List* create_empty_list(void)
{
	Linked_List* new_head; 
	new_head = (Linked_List*)malloc(sizeof(Linked_List)); 
	new_head->head = NULL;
	
	return new_head;
}

/*------------------------------------------------------------------*/
	
Node* insert_end(Linked_List* list, void* data)
{
	Node* new_node;
	Node* temp;
	new_node = (Node*)malloc(sizeof(Node));
	new_node->data = malloc(sizeof(char*));
	new_node->data = (char*)data;
	new_node->next = NULL;
	if(list->head == NULL)
	{
		list->head = new_node;
	}
	else
	{
		temp = list->head;
		while(temp->next != NULL)
		{
			temp = temp->next;
		}
		
		temp->next = new_node;
	}
	return(list->head);
}
	
/*------------------------------------------------------------------*/	

void display(Linked_List* list)
{
	Node* temp;
	temp = list->head;
	while(temp != NULL)
	{
		printf("%s ", temp->data);
		temp = temp->next;
	}
}

/*------------------------------------------------------------------*/
		
void free_list(Linked_List* list)
{
	while(list->head != NULL)
	{
		Node* temp = list->head;
		list->head = temp->next;
		free(temp);
	}
}

/*------------------------------------------------------------------*/
/*Main code to test linked list*/	
	
int main(void)
{
	
	/*int num_elements, i;*/
	char str[20];
	
	Linked_List* char_list = create_empty_list();
	
	printf("Enter a word\n");
	scanf("%s", str);
	
	char_list->head = insert_end(char_list, str);
	
	
	printf("The list is: ");
	display(char_list);
	printf("\n\n");
	
	
	free_list(char_list);
	
	return(0);
	
}
Posted
Updated 20-Oct-17 21:31pm

1 solution

Try:
printf("%s ", (char*)(temp->data));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900