错误:从'char'到'char*'的转换无效

error: invalid conversion from 'char' to 'char*'

本文关键字:char 转换 无效 错误      更新时间:2023-10-16

我有一个小问题。我不断收到此错误:错误:这部分代码从"char">到"char*"的转换无效(list<lst>* listSearch(list<lst> *LST, char* wrd, KEY key)(。

我在这里做错了什么?

enum KEY {code, disease} key;
struct lst
{
    char *_code;
    char *_disease;
    lst* next;
};

bool isPartOf(char* word, char* sentence)
{
    unsigned int i=0;
    unsigned int j=0;
    for(i;i < strlen(sentence); i++)
    {
        if(sentence[i] == word[j])
        {
            j++;
        }
    }
    if(strlen(word) == j)
        return true;
    else
        return false;
}
list<lst>* listSearch(list<lst> *LST,char* wrd,KEY key)
{
    list<lst> resultList;
    list<lst>* result;
    switch(key)
    {
    case code:
        for(list<lst>::iterator i = LST->begin(); i != LST->end(); i++)
        {
            if(isPartOf(wrd, *i._code))
            {
                resultList.push_back(*i);
            }
        }
        break;
    case disease:
        for(list<lst>::iterator i = LST->begin(); i != LST->end(); i++)
        {
            if(isPartOf(wrd, *i->_disease))
                resultList.push_back(*i);
        }
        break;
    }
    result = &resultList;
    return result;
}

它看起来像一个编译器错误。至少编译器应发出另一条错误消息。

该问题与操作员优先级有关。此声明

if(isPartOf(wrd, *i._code))

必须写成

if(isPartOf(wrd, ( *i )._code))

似乎编译器为此语句发出了错误

if(isPartOf(wrd, *i->_disease))

它必须写成

if(isPartOf(wrd, i->_disease))

因为表达式 *i->_disease 具有 char 类型,但您必须将类型为 char * 的对象传递给函数

使用此函数可能会导致未定义的行为,因为它返回指向本地对象的指针。

list<lst>* listSearch(list<lst> *LST,char* wrd,KEY key)
{
    list<lst> resultList;
    list<lst>* result;
    //...
    result = &resultList;
    return result;
}

考虑到函数isPartOf在逻辑上是错误的。例如,当word等于"ab"并且sentence等于"a1111b"时,函数将返回true。我不认为你的意思是这个逻辑。