c - 对指针没有影响的语句

标签 c arrays pointers struct compiler-warnings

我有 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);

}

warning: assignment makes integer from pointer without a cast [-Wint-conversion] search_result = (search_hashtag(head, buffer));

warning: comparison between pointer and integer if (search_result!=NULL){

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

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

最佳答案

函数中有几个错误。

首先不清楚什么是变量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
}

缓冲区->文本的内存未分配。所以这个说法

strcpy(buffer->text,word);

有未定义的行为。

变量 search_result 被声明为类型 int。您应该将它与整数而不是指针进行比较

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

看来,如果主题标签已经存在,则不应将新的主题标签添加到此语句的列表中

new_hashtag(buffer);

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

关于c - 对指针没有影响的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37224889/

相关文章:

c - 如何从 C 数组中提取数字/字节?

java - 将字符串数组转换为数组列表

无法读取C中的结构数组

c - 当我释放分配的内存时出现 munmap_chunk() 错误

c - 如何在c中声明链表

c - pread 和 pwrite 未定义?

c - 为什么第五个数据不能工作fscanf()有问题吗?

c - 常量字符串将存储在内存中的什么位置?

javascript - 比较两个数组中的对象并根据 JavaScript 中的匹配返回

c++ - 指针间接寻址对效率的影响有多大?