2016-05-14 113 views
0

我有使用指针2层结构没有影响,形成一个链表,我创建了这些工种操作:声明与指针

typedef struct hashtag { 
    char *text; 
    int count; 
} *Item; 

typedef struct node { 
    Item item; 
    struct node *next; 
} *link; 

我在与所有的指针一对夫妇的问题相同的功能。

/* adds hashtag (Item Type) to linked list (Link Type) */ 

void add_hashtag(char *word){ 
    int search_result, i; 
    for (i = 0; i < strlen(word); i++) 

    /* converts word to all lowercase before adding */ 

    token[i]=tolower(*(token + i)); 
    Item buffer = (Item) malloc(sizeof(struct hashtag)); 
    strcpy(buffer->text,word); 

    /* Runs through the list to see if the hashtag was already added */ 

    search_result = (search_hashtag(head, buffer)); 
    if (search_result!=NULL){ 

     /* Increase count (occurrence) of hashtag if it already exists (returns link type or NULL if not found) */ 

     increase_hashtag_count(search_result); 
    } 

    /* Create new struct type hashtag */ 
    new_hashtag(buffer); 

} 

警告:赋值时将指针整数,未作施放[-Wint转换] search_result =(search_hashtag(头,缓冲液));

警告:(!search_result = NULL)指针和整数 如果进行比较{

tolower()功能和search_result()不与指针正常工作,而且我无法调试这一点。

编辑:tolower()固定的,我误读的文档

+0

[请参阅此讨论关于为什么不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+0

'int search_result'但它需要一个指针。 'strcpy(buffer-> text,word);':'buffer-> text'不分配。 – BLUEPIXY

回答

0

作为每tolower()man page

返回的值是转换后的信,或c如果转换是不可能的。

这意味着,它不变化传递的参数,它return S中的结果作为函数调用的返回值和你的情况,你忽略了返回值,使得整个函数调用毫无意义。

所以,你需要有另一个数组存储的tolower()返回值来获取转换后的小写

这就是说,对于第二种情况,您已经定义search_resultint但后来,你想它比对NULL,这是一个空指针常量。您需要相应地更正数据类型。

+0

是的,我以某种方式完全误读了文档,现在我已经解决了这些问题,但搜索结果中的其他问题仍然存在 – spacing

+0

@spacing:那么还存在什么问题?你只能说他们'工作不正常'。 – usr2564301

+0

@RadLexus(search_hashtag)/ search_result()无法正常工作,主帖 – spacing

1

函数中有几个错误。

首先,目前还不清楚什么是可变token哪里以及如何声明,使用和设置

for (i = 0; i < strlen(word); i++) 

/* converts word to all lowercase before adding */ 

token[i]=tolower(*(token + i)); 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

希望检查调用malloc是全成。例如

Item buffer = (Item) malloc(sizeof(struct hashtag)); 
if (buffer) 
{ 
    //...other stuff 
} 

buffer-> text的内存未分配。所以这个声明

strcpy(buffer->text,word); 

有未定义的行为。

变量search_result被声明为具有类型int。你应该把它与一个整数,而不是一个指针比较

search_result = (search_hashtag(head, buffer)); 
if (search_result!=NULL){ 
^^^^^^^^^^^^^^^^^^^^^^^^^ 

看来,如果主题标签已经存在,你不应该在此声明一个新的主题标签添加到列表中

new_hashtag(buffer); 

这足以增加现有主题标签的计数(发生)。

+0

相同错误非常好的帮助,非常感谢!关于缓冲区 - >文本分配,你可以再澄清一点吗?通过使用'Item buffer =(Item)malloc(sizeof(struct hashtag));'我没有为Item.count和Item.text变量分配内存吗? 关于search_hashtag(),如果尚未找到,则返回NULL。所以!= NULL = new_hashtag(); 但我不知道如何正确调用指针 – spacing

+0

@spacing结构hashtag有两个数据成员计数和指针文本将指向字符串单词,据我所知。所以你需要为单词的副本分配内存。例如buffer-> text = malloc(strlen(word)+ 1); 。至于函数serach_hashtag,那么你应该确定它有什么样的返回类型。 –