gpt4 book ai didi

c - 如何将枚举值传递到结构中

转载 作者:太空宇宙 更新时间:2023-11-04 03:33:57 24 4
gpt4 key购买 nike

我的问题是我需要将参数 (instType, typ1, *op1...) 的值传递给结构类型 tInst。

我确信这是一个微不足道的问题,但我已经花了大约 3 个小时来解决它。

GCC 返回段错误 11。

我的 .h 文件

typedef enum tInstCode {

I_ADD=0, // (dest, addr, addr) +
I_SUB, // (dest, addr, addr) -
I_MUL, // (dest, addr, addr) *
I_DIV, // (dest, addr, addr) /

} tInstCode;



typedef enum TypeI{
INT=0,
DOUBLE,
STRING
} TypeI;


typedef struct iOperand
{
TypeI type;
void *content;
} iOperand;

typedef struct tInst
{
tInstCode instType;
iOperand *op1;
iOperand *op2;
iOperand *res;
} tInst;

typedef struct ListItem
{
tInst Instruction;
struct ListItem *NextItem;
} tListItem;

我的主文件:

void generateInstruction(tInstCode instType, TypeI typ1,  void *op1, TypeI typ2, void *op2, TypeI typ3, iOperand *op3 )

{

tListOfInstr list;
listInit(&list); //list defined in another file
tInst* I;

I->instType = instType;
I->op1->type = typ1;


I->op1->content = op1;

I->op2 -> type = typ2;
I->op2 -> content = op2;

I->res -> type = typ3;
I->res -> content = op3;
listInsertLast(&list, *I);

}


int main(int argc, char** argv)
{
int a;
a=8;
int *b;
b = &a;

int c;
c=1;
int *d;
d = &c;

generateInstruction(0, DOUBLE, *b, INT, *d, INT, NULL);


}

最佳答案

tInst* I;

I->instType = instType;

您没有为 I 分配内存。

目前 I 只是一个具有(可能)随机值的指针。使用 malloc 获取具有空闲内存的合适地址。

可以这样做:

tInst* I;
I = malloc(sizeof(tInst));
I->op1 = malloc(sizeof(iOperand));
I->op2 = malloc(sizeof(iOperand));
I->res = malloc(sizeof(iOperand));

不过请记住,malloc 可能会失败,因此您需要检查 NULL 的返回值。

关于c - 如何将枚举值传递到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34047870/

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