声明对指针没有影响

时间:2016-05-14 09:19:39

标签: c arrays pointers struct compiler-warnings

我有两个使用指针形成链表的结构,我正在创建适用于这些类型的操作:

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-conversion]     search_result =(search_hashtag(head,buffer));

     

警告:指针和整数之间的比较     if(search_result!= NULL){

tolower()函数和search_result()无法正确使用指针,我在调试时遇到问题。

编辑:tolower()已修复,我误读了文档

2 个答案:

答案 0 :(得分: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
}

未分配缓冲区&gt;文本的内存。所以这句话

strcpy(buffer->text,word);

有未定义的行为。

变量search_result被声明为类型int。你应该将它与整数而不是指针

进行比较
search_result = (search_hashtag(head, buffer));
if (search_result!=NULL){
^^^^^^^^^^^^^^^^^^^^^^^^^

似乎如果hashtag已存在,则不应在此语句的列表中添加新的主题标签

new_hashtag(buffer);

增加现有主题标签的计数(发生)就足够了。

答案 1 :(得分:0)

根据tolower()的{​​{3}},

  

返回的值是转换后的字母的值,如果无法转换,则返回c

这意味着,它不会更改传递的参数,它return结果作为函数调用返回值,在您的情况下,您忽略了返回值,整个函数调用毫无意义。

因此,您需要使用另一个数组来存储tolower()的返回值,以获取转换后的小写字符串

也就是说,对于第二种情况,您已将search_result定义为int但后来,您尝试将其与NULL进行比较,后者是一个空指针常量。您需要相应地更正数据类型。