Click here to Skip to main content
15,889,403 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am transferring a linked list of chars into an array of chars, and when I print out the array of chars, i get, along with the string, a garbage int value as such:

2
this0
is1
the6
userfile1
and1
all0
of1
the3
words1
are7
seperated0
by-1
a8
whitespace

I am unsure as to where I must place the null character line in my code.

What I have tried:

fgets(str2, user_file_length, user_file);/*need to assign str2[user_file_length]*/
	token = strtok(str2, " ");
	
	while(token != NULL)
	{
		/*printf( " %s\n", token );*/
		user_list->head = insert_word(user_list, token);
    	token = strtok(NULL, " ");
	}
	printf("\nThe userfile linked list is:\n ");
	display(user_list);
	printf("\n\n");
	
	num_user_words = count(user_list);
	/*code to put userfile linked list into dynamically allocated array*/
	user_array = (char**)malloc(num_user_words*sizeof(char*));
	for(i=0;i<num_user_words;i++)
	{
		put_in_array(user_list, i, user_array);
		printf("\n %s", user_array[i]);
	}


Node* insert_word(Linked_List* list, void* word)
{
	Node* new_node;
	Node* temp;
	char* ptr = malloc(sizeof(word));/*need to free*/
	strcpy(ptr, word);
	new_node = (Node*)malloc(sizeof(Node));/*need to free*/
	new_node->data = ptr;
	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 put_in_array(Linked_List* list, int element, char** array)
{
	int length;
	int count = 0;
	Node* temp;
	temp = list->head;
	
	while(temp != NULL)
	{
		if(count == element)
		{
			length = strlen((char*)(temp->data))-2;
			printf("%d", length);
			array[count] = (char*)malloc(length*sizeof(char*));
			array[count] = (char*)(temp->data);
			
		}
		count++;
		temp = temp->next;
	}
	
}
Posted
Updated 21-Oct-17 19:36pm

1 solution

How often do we have to tell you to use the debugger? This would have shown you immediately where the number is coming from...

It's there because you put it there:
void put_in_array(Linked_List* list, int element, char** array)
{
...
			length = strlen((char*)(temp->data))-2;
			printf("%d", length);
			array[count] = (char*)malloc(length*sizeof(char*));
...	
}
 
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