我在哪里将NULL字符放在我的函数中? [英] Where do I place the NULL character in my function?

查看:64
本文介绍了我在哪里将NULL字符放在我的函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个字符串链接转移到一个字符数组中,当我打印出字符数组时,我和字符串一起得到一个垃圾int值:



2

this0

is1

the6

userfile1

和1

all0

of 1

the3

words1

are7

分离0

by-1

a8

whitespace



我不确定我必须在我的代码中放置空字符行。



我尝试了什么:



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;
	}
	
}

推荐答案

我们多久要告诉您使用调试器?这会立刻向你展示这个号码的来源......



它就在那里,因为你把它放在那里:

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*));
...	
}


这篇关于我在哪里将NULL字符放在我的函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆