繁体   English   中英

不兼容的类型 struct* 和 struct,

[英]Incompatible types struct* and struct,

感谢您花时间阅读我的问题,我查看了一些类似的问题,它们在这种情况下似乎没有帮助,尽管可能会帮助其他遇到类似问题的人:

C:不兼容的类型?
结构为 C 中不兼容的指针类型
结构 C 的不兼容类型错误

我正在尝试在 c (-std=c99) 中创建一个简单的链表结构,此时我的结构相当通用:

typedef struct
{
  int count;
  char* word;
  struct node *nextNode;
}node;

然后在一个函数中,我有一个“根”或“头”节点:

node *root;
root = (node *) malloc(sizeof(node));

我尝试稍后在函数中将节点分配给node nextNode ,如下所示:

if(root->nextNode == 0)
{
  root->nextNode = foo;
}

这导致错误:
“从类型node分配到类型struct node*时,错误不兼容类型
&foo不会改善这种情况,而是导致lvalue required as unary样式错误。

这是围绕我的问题的上下文:

    #include <stdio.h>
    #include <malloc.h>
    #include <string.h>

    typedef struct
    {
        int count;
        char* word;
        struct node *nextNode;
    }node;

    node makenode(char *word)
    {
        node x;
        x.word = word;
        x.count = 1;
        return x;
    }

    void processInput(int threshold, const char* filename)
    {   
        node *root;
        root = (node *) malloc(sizeof(node)); 
        root->nextNode = 0;  
        char* word;
        while(fgets(word, 29, stdin) != NULL){
            if(root->nextNode == 0)
            {
                root->nextNode = makenode(word);
            }

问题

    typedef struct             // make an alias for a structure with no tag name
    {
        int count;
        char* word;
        struct node *nextNode; // with a pointer to struct node (which does not exit)
    }node;                     // name the alias node

解决方案

    typedef struct node        // make an alias for a structure with tag name node
    {
        int count;
        char* word;
        struct node *nextNode; // with a pointer to struct node (which is this one)
    }node;                     // name the alias node

试试这个代码

     #include <stdio.h>
    #include <malloc.h>
    #include <string.h>

    typedef struct node //should give a name for this 
    {
        int count;
        char* word;
        struct node *nextNode;
    }node;

    static node *makenode(char *word) //start with static and returning type is node* because we are storing this output in root->nextNode which is *node pointer
    {
        node x;
        x.word = word;
        x.count = 1;
        return x;
    }

    void processInput(int threshold, const char* filename)
    {   
        node *root;
        root = (node *) malloc(sizeof(node)); 
        root->nextNode = NULL;  //pointer values should initialised to NULL not 0
        char* word;
        while(fgets(word, 29, stdin) != NULL){
            if(root->nextNode == NULL) ////pointer values should initialised to NULL not 0
            {
                root->nextNode = makenode(word);
            }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM