gpt4 book ai didi

c - 如果此代码中 consed 对象的 car 和 cdr 是整数,如何打印它们?

转载 作者:行者123 更新时间:2023-11-30 21:11:47 25 4
gpt4 key购买 nike

我正在尝试构建一个在 c 中实现方案的交叉编译器。为此,我尝试使用 cons 和列表来实现基本方案结构。下面显示的代码是针对缺点的。当 consed 对象是整数而不是另一个 consed 对象时,我无法访问它的汽车。

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

typedef enum
{PAIR, NUMBER} object;

typedef struct node cons_object;

struct node {
object type;
union
{
int i;
float f;
char* string;
struct pair {
cons_object* car;
cons_object* cdr;
} pair;
} data;
};

cons_object* cons(cons_object* x, cons_object* y)
{
cons_object* obj;
obj = malloc(sizeof(cons_object*));
obj->type = PAIR;
obj->data.pair.car = x;
obj->data.pair.cdr = y;
return obj; /*returns the pointer car*/
}

cons_object* car(cons_object* list) /*takes in a consed object*/
{
cons_object* y;
y = list->data.pair.car;
return y; /* returns the pointer of another consed object */
}

cons_object* cdr(cons_object* list)
{
cons_object* z;
z = list->data.pair.cdr;
return z; /* returns the pointer of another consed object */
}

void eval_cons(cons_object* pair)
{
cons_object* first;
cons_object* second;
int *a; /* An integer type pointer to dereference the values returned by car and cdr pointers */

first = car(pair);
second = cdr(pair);
{
if(first->type == PAIR){
eval_cons(first); // If car is a cons-ed object, it is again sent to the eval function
}
else
{
a = (int *)&first; /* tried type casting too */
printf("%d",*a);
}
}
if(second->type == PAIR)
eval_cons(second); // If cdr is a cons-ed object, it is again sent to the eval function

else
{
a = (int *)&second;
printf("%d",*a); // prints the dereferenced value
}
}

// If eval starts working then we could test it from the following sample code:


int main ()

{
eval_cons(cons(3,4)); /* cant find a way to access 3 and 4 */
getchar();
return 0;
}

最佳答案

eval_cons(cons(3,4));

也许,应该是

cons_object a = { NUMBER, .data.i = 3};
cons_object b = { NUMBER, .data.i = 4};
eval_cons(cons(&a, &b));

还有

int a;
a = first->data.i;//also second
printf("%d ",a);

关于c - 如果此代码中 consed 对象的 car 和 cdr 是整数,如何打印它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17841065/

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