首页 > 解决方案 > 当我实际上需要执行两次时,编译器需要取消引用一次。“从不兼容的类型分配给结构;删除 *”

问题描述

我有以下代码。我知道那是错误的,但问题是我不明白为什么。下面我解释一下我的疑惑。

#include <stdio.h>


struct mychar {
    char value;
    struct mychar *nextPtr;
};

typedef struct mychar Mychar;


void insert(Mychar **, char );    // line 19
void printlist(Mychar **);


int main(){
    Mychar *startPtr = NULL;

    insert(&startPtr, 'b');

    printlist(&startPtr);

}


void insert(Mychar **sPtr, char myvalue){
    Mychar *newlinkPtr = calloc(1, sizeof(Mychar));

    if (**sPtr == NULL){    // if I put two ** I get errors
        newlinkPtr->value = myvalue;
        newlinkPtr->nextPtr = **sPtr;    // same here
        **sPtr = newlinkPtr;    // same here
    }
}


void printlist(Mychar **startPtr){
    printf("%c\n", *startPtr->value);    // get error
}

以下是错误:

liste_collegate.c:29:13: error: invalid operands to binary expression ('Mychar' (aka 'struct mychar') and 'void *')
        if (**sPtr == NULL){
            ~~~~~~ ^  ~~~~
liste_collegate.c:31:23: error: assigning to 'struct mychar *' from incompatible type 'Mychar' (aka 'struct mychar'); remove *
                newlinkPtr->nextPtr = **sPtr;
                                    ^ ~~~~~~
liste_collegate.c:32:10: error: assigning to 'Mychar' (aka 'struct mychar') from incompatible type 'Mychar *' (aka 'struct mychar *'); dereference with *
                **sPtr = newlinkPtr;
                       ^ ~~~~~~~~~~
                         *
liste_collegate.c:38:26: error: member reference base type 'Mychar *' (aka 'struct mychar *') is not a structure or union
        printf("%c\n", *startPtr->value);

我的疑问

标签: cpointersdata-structuresstructlinked-list

解决方案


首先为您的insert功能:

void insert(Mychar **sPtr, char myvalue){
    Mychar *newlinkPtr = calloc(1, sizeof(Mychar));

    if (**sPtr == NULL){    // if I put two ** I get errors
        newlinkPtr->value = myvalue;
        newlinkPtr->nextPtr = **sPtr;    // same here
        **sPtr = newlinkPtr;    // same here
    }
}

sPtr具有类型Mychar **:指向指针的指针。

*sPtr有类型Mychar *:指向类型的指针Mychar

现在,当您使用**sPtrhas type时Mychar:具有 type 的值Mychar

NULL用于指针而不是值。因此,如果要比较,可以使用sPtrwithNULL*sptrwith进行比较NULL。您不应将该值**sPtrNULL. 顺便说一句,你的功能可以变成这样:

void insert(Mychar **sPtr, char myvalue){
    Mychar *newlinkPtr = calloc(1, sizeof(Mychar));
    if (!newlinkPtr) {return;} // you should check the return value of calloc funciton because it may be failed

    if (*sPtr == NULL) {  
        newlinkPtr->value = myvalue;
        newlinkPtr->nextPtr = *sPtr;   
        *sPtr = newlinkPtr;  
    }
}

对于打印功能:

void printlist(Mychar **startPtr){
    printf("%c\n", *startPtr->value);    // get error
}

*startPtr->value应更改为(*startPtr)->value.

但是,使用 print 函数,您不需要使用指向指针的指针,因为在此函数中,您不会更改或更新任何内容。您可以将指针用作:

void printlist(Mychar *startPtr){
    printf("%c\n", startPtr->value);
}

如果你这样做,在 main 函数中,当你调用 print 函数时:

printlist(startPtr);

推荐阅读