gpt4 book ai didi

C LinkedList 示例无法编译

转载 作者:行者123 更新时间:2023-12-02 08:49:21 25 4
gpt4 key购买 nike

下面的C代码是我自己写的原始链表的方法。它使用一个名为 lnode 的结构。我知道这不是最好/最有效的方法,但我的想法是:创建基节点,使用“迭代器”指针,这里是 q,它指向列表中的最后一个节点,然后添加一个新节点.

以下代码将无法编译。我找不到原因,但它讨厌这一行

struct lnode *q= malloc(sizeof(struct lnode));

关于实现这个想法有什么建议吗?提前致谢。

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

struct lnode{
int value;
struct lnode *nextnode;

};

int main(){

struct lnode *startnode = malloc(sizeof(struct lnode));
startnode->value=0;
startnode->nextnode=NULL;

struct lnode *q= malloc(sizeof(struct lnode));

int i = 0;

for(i=0;i<10;i++){

struct lnode *p = malloc(sizeof(struct lnode));
p= q->nextnode;
p->value=i;
p->nextnode=NULL;
q=p;


}


return 0;


}

我想指出我是新手。我正在使用 Watcom 编译器(为什么?我的电脑很旧,我只需要这些练习程序)日志输出是

structure1.c(17): Error! E1063: Missing operand structure1.c(17):

Warning! W111: Meaningless use of an expression structure1.c(17):

Error! E1009: Expecting ';' but found 'struct' structure1.c(17):

Error! E1011: Symbol 'lnode' has not been declared structure1.c(17):

Error! E1011: Symbol 'q' has not been declared structure1.c(17):

Error! E1014: Left operand must be an 'lvalue' structure1.c(19):

我按照给出的建议更改了代码,新代码是这样的:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

struct lnode{
int value;
struct lnode *nextnode;

};

int main(){

struct lnode *startnode = (struct lnode *)malloc(sizeof(struct lnode));
struct lnode *q;
startnode->value=0;
startnode->nextnode=NULL;

q = malloc(sizeof(struct lnode));


doLoop(q);

return 0;


}

void doLoop(struct lnode *q){

int i = 0;

for(i=0;i<10;i++){

struct lnode *p = (struct lnode *)malloc(sizeof(struct lnode));
q->nextnode=p;
p->value=i;
p->nextnode=NULL;
printf("%i, %i\n",p->value,q->value);
q=p;

}
}

我打印了列表中每个节点的“值”值以及先前的值。除了第一次迭代会产生奇怪的输出外,它可以正常工作。

最佳答案

我怀疑编译器(例如 Microsoft 编译器)仅支持 C89 标准,不允许混合代码和声明。将 q 的声明移至范围顶部:

int main(){

struct lnode *startnode = (struct lnode *)malloc(sizeof(struct lnode));
struct lnode *q
startnode->value=0;
startnode->nextnode=NULL;

q = malloc(sizeof(struct lnode));

关于C LinkedList 示例无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9687457/

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