gpt4 book ai didi

c - 用 C 编写打印方法

转载 作者:行者123 更新时间:2023-12-04 05:27:44 26 4
gpt4 key购买 nike

我是 C 的新手,正在为 Scheme 制作解释器。我试图获得一个合适的 printList 方法来遍历结构。

该程序接受如下输入:

(a (b c))



并在内部将其表示为:
[""][ ][ ]-->  [""][ ][/]
| |
["A"][/][/] [""][ ][ ]--> [""][ ][/]
| |
["B"][/][/] ["C"][/][/]

现在,我只想让程序接受输入,在内部制作适当的单元格结构并打印出单元格结构,从而得到

(a (b c))



最后。

这是我的结构:
typedef struct conscell *List;

struct conscell {
char symbol;
struct conscell *first;
struct conscell *rest;

};


void printList(char token[20]){
List current = S_Expression(token, 0);

printf("(");

printf("First Value? %c \n", current->first->symbol);
printf("Second value? %c \n", current->rest->first->first->symbol);
printf("Third value? %c \n", current->rest->first->rest->first->symbol);


printf(")");

}

在 main 方法中,我获取第一个 token 并调用:

printList(token);



我再次测试了子列表的值,我认为它有效。但是,我需要一种方法来遍历整个结构。请再次查看我的 printList 代码。打印调用是我必须输入的,以手动获取 (a (b c)) 列表值。所以我得到这个输出:

First value? a

First value? b

First value? c



这是我想要的,但我想要一种使用循环来完成它的方法,无论结构多么复杂,还要在适当的地方添加括号,所以最后,我应该得到:

(a (b c))



这与输入相同。

任何人都可以帮我解决这个问题吗?

最佳答案

List 的类型是 struct conscell 的指针,因此 createList 函数中的 malloc() 应该是 sizeof(struct conscell):

List node = malloc(sizeof(struct conscell));

指向结构的指针只有 8 字节,而结构本身的大小是 17(默认填充实际上是 24 字节):

http://en.wikipedia.org/wiki/Data_structure_alignment

关于c - 用 C 编写打印方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13004153/

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