C错误:编译时请求成员错误
我第一次用C语言编译时遇到了很多错误。我是C语言编程新手。我如何解决这个问题以及为什么会发生这种情况 我的源代码:C错误:编译时请求成员错误,c,debugging,struct,compiler-errors,C,Debugging,Struct,Compiler Errors,我第一次用C语言编译时遇到了很多错误。我是C语言编程新手。我如何解决这个问题以及为什么会发生这种情况 我的源代码: #include <stdio.h> #include <stdlib.h> struct n{ int x; n *next; }; typedef n node; int main(){ node *root; root = (node *)malloc(sizeof(node)); root->x =
#include <stdio.h>
#include <stdlib.h>
struct n{
int x;
n *next;
};
typedef n node;
int main(){
node *root;
root = (node *)malloc(sizeof(node));
root->x = 10;
root->next = (node *)malloc(sizeof(node));
root->next->x = 20;
printf("%d", root->next->x);
node *iter;
iter = root;
return 0;
}
但是当我使用C语言中的g++编译到您想要使用结构类型时,没有问题。必须使用结构类型前缀
struct
。通常的做法是为结构定义类型别名,以避免一直这样做。因此,您的代码应该如下所示:
struct n{
int x;
struct n * next;
};
typedef struct n node;
< C++ >不需要预先准备<代码>结构> /代码>(或定义额外类型别名),以便同一代码用G++编译好.< /p> 将结构定义更改为:
struct n {
int x;
struct n *next;
};
typedef struct n node;
其中,我在
n
之前添加了struct
关键字。你必须这样做,但是你可能会混淆C++,不需要你这样做。 < P>//这编译成C程序,并给出值20作为输出:
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main()
{
struct node *root;
root = (struct node *) malloc(sizeof(struct node));
root->x = 10;
root->next = (struct node *) malloc(sizeof(struct node));
root->next->x = 20;
printf("%d", root->next->x);
struct node *iter;
iter = root;
}
#包括
#包括
结构节点{
int x;
结构节点*下一步;
};
int main()
{
结构节点*根;
root=(结构节点*)malloc(sizeof(结构节点));
根->x=10;
root->next=(结构节点*)malloc(sizeof(结构节点));
根->下一步->x=20;
printf(“%d”,root->next->x);
结构节点*iter;
iter=根;
}
<> C语言在引用Stutt变量时需要
引入了一个名为n
的新类型,即使在手头的struct
-定义中也可以立即使用该类型,因此n*next
已经引用了现有类型。(注意,C++中的<代码>结构> <代码>和<代码>类< /代码>几乎相同。
C标准在描述规范的哪一部分实际上是类型名称时没有那么清楚(例如,参见此):
6.7.2.1结构和联合规范
(7) 。。。关键字struct和union表示类型为
指定的类型分别是结构类型或联合类型
(8) 结构声明列表在
结构或联合说明符在翻译中声明新类型
单位。。。直到终止列表的}之后,类型才是不完整的,然后才是完整的
但是实际上,struct n{..}
引入了一种新类型,它是通过关键字struct
和名称n
识别的,即通过struct n
旁注:一件有趣/有趣的事情可能是,即使在结构定义中直接引用struct n
,也指的是一个不完整的类型,即struct n
是一个向前声明,直到包含}
。只有与结构的前向声明的定义结合在一起,struct n*next
才是有效的
通常的做法是通过typedef
“手动”引入别名,即typedef结构n节点
,这样节点
单独具有与struct n
相同的含义。别名通常与结构本身一起定义。因此,您的C代码可以按如下方式工作:
typedef struct n{
int x;
struct n *next;
} node;
这段代码似乎有一个更基本的错误():prog.c:6:5:错误:未知类型名“n”:n*next代码>。此n*下一步代码>应该是struct n*next代码>typedef n节点代码>-->typedef结构n节点代码>(还有一个强烈的建议,在需要之前不要使用typedef。它们令人困惑,而且很少需要)总是从顶部开始读取编译器消息。永远不要因为你认为自己理解一条信息多于另一条信息而忽略第一条信息。后期消息通常是早期消息的副作用。修复第一个错误,以后的错误通常会自行消失。使用javac编译时有问题吗?欢迎使用堆栈溢出。我相信你说的是真的,但是除非你解释为什么你的代码能工作而原始代码不能,那有什么意义呢?这不是玩“发现差异”的地方。@RobKennedy谢谢Rob!添加了所需的解释。A-用于彻底性和解释。
typedef struct n{
int x;
struct n *next;
} node;