我有 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/