gpt4 book ai didi

c - 不兼容的类型 struct* 和 struct,

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:37 25 4
gpt4 key购买 nike

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

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;

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

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

关于c - 不兼容的类型 struct* 和 struct,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25707934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com