不兼容的类型struct *和struct,

时间:2014-09-07 07:07:51

标签: c pointers struct incompatibletypeerror

感谢您抽出宝贵时间阅读我的问题, 我已经看了几个类似的问题,在这种情况下他们似乎没什么帮助 虽然可以帮助其他类似的麻烦:

C: Incompatible types?
   Struct as incompatible pointer type in C
   Incompatible Types Error with Struct C

我试图在c(-std = c99)中创建一个简单的链表结构, 我的结构在这一点上相当通用:

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

然后在一个函数中我有一个" root"或者"头部"节点:

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

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

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

导致错误:
    "从类型struct node*分配到类型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);
            }

2 个答案:

答案 0 :(得分:2)

问题

    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

答案 1 :(得分:0)

尝试此代码

     #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);
            }
}