我是C语言的新手,正在构建一个小型Scheme解释器的早期阶段。在这个项目的这一部分中,我正在尝试构建一个简单的cons单元数据结构。它应该像这样内部表示:
为了测试它是否正常工作,我有一个打印函数来输出输入。以下是不起作用的代码:
(a b c)
并将其表示为:
[ ][ ] -> [ ][ ] -> [ ][/]
| | |
A B C
为了测试它是否正常工作,我有一个打印函数来输出输入。以下是不起作用的代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "lexer.h"
#include "parse.h"
char token[20];
struct conscell {
char *data;
struct conscell *first, *rest;
};
void S_Expression ()
{
/* function from lexer to receive input a split into tokens no greater than 20 */
startTokens(20);
/* gets the next token */
strcpy(token, getToken());
/* List is a typedef for the struct conscell */
List tree = createList ();
tree = nextNode (tree);
printList(tree);
}
List createList ()
{
List node = malloc(sizeof (List));
if (node == NULL) {
printf("Out of memory!\n");
exit(1);
}
node->data = NULL;
node->first = NULL;
node->rest = NULL;
return node;
}
/* Recursive function to build cons cell structure */
List nextNode (List node)
{
node = createList ();
if (token[0] == '(')
{
strcpy(token, getToken());
node->first = nextNode(node->first);
node->rest = nextNode(node->rest);
}
else
{
if (token[0] == ')')
{
node = NULL;
}
else
{
List temp = createList();
temp->data = token;
temp->first = NULL;
temp->rest = NULL;
node->first = temp;
strcpy(token, getToken());
node->rest = nextNode(node->rest);
}
}
return node;
}
/* Prints output. So far, just trying to print symbols */
void printList(List node)
{
if (node != NULL)
{
if (node->data != NULL)
{
printf("%s", node->data);
}
}
}
到目前为止,什么都无法打印出来。我几乎可以确定这是一个指针问题。如果有人能够指点我(没有双关语),那将不胜感激。
谢谢。
car
和cdr
。nextNode
中也存在内存泄漏问题。你还在将指针复制到随后被覆盖的缓冲区中。 - Fred Foo