我正在尝试构建一个简单的程序集模拟器。 我正在尝试创建set函数;该函数将采用2个参数(字符串数组)arg1& ARG2。 然后它会将字符串与一个字符串数组进行比较,这是一个函数指针的arraylist的索引。
我遇到的问题是当我尝试设置寄存器的值时。 我尝试过该系列的许多变种:
*register_ptr[i] = *(int*)(atoi(arg2));
没有成功;有什么我不理解的吗?
希望代码更清晰:
int opcode_set(char* opcode, char *arg1, char *arg2)
{
int i, j;
//printf("%d\n", (int)arg2);
for(i=0;i<4;i++)
{
if(!strcmp(arg1, register_str[i]))
{
for(j=0;j<4;j++)
{
if(!strcmp(arg2, register_str[i]))
{
*register_ptr[i] = *(int*)register_ptr[j];
}
else
{
*register_ptr[i] = *(int*)(atoi(arg2));
}
}
}
}
//printf("%d", *register_ptr[i] );
INSP++; /* NOP does not do anything except moving the instruction pointer to the next instruction */
return (0);
}
编辑: register_str&amp;的声明register_ptr:
const char *register_str[] = {"REGA", "REGB", "REGC", "REGX"};
int *register_ptr[]={®A, ®B, ®C, ®X};
我使用两个数组来决定哪个操作码,一个字符串数组和一个函数指针数组,我通过字符串索引并使用相同的索引位置来调用该函数:
int exec_instruction(char *instruction){
int i; //used for indexing
/* the line below may be useful for debugging to see the current instruction*/
/*printf("executing line: %s", instruction);*/
/* three variables could be used to extract opcode and
arguments from the variable instruction */
char *opcode = NULL;
char *arg1 = NULL;
char *arg2 = NULL ;
char *copy = NULL;
/* we need here some functionality to extract opcode,
arg1 and arg2 from the string instruction*/
copy = strdup(instruction);
opcode = strtok(copy," \n\r");
arg1 = strtok(NULL," \n\r");
arg2 = strtok(NULL," \n\r");
/* Now we have to call the right function corresponding
to the right opcode For example: */
for(i = 0; i < 10; i++)
{
if(!strcmp(opcode_str[i], opcode))
(*opcode_func[i])(opcode,arg1,arg2);
}
/* for demonstration purpose we execute NOP independent of input
this line must go in your implementation */
(*opcode_func[0])("NOP",NULL,NULL);
/* return value should be 0 if execution was ok otherwise -1*/
return(0);
}
我说的两个数组:
const char *opcode_str[] = {"NOP", "SET", "AND", "OR", "ADD", "SUB", "SHL", "SHR", "JMP", "PRT"};
opcode_function opcode_func[] = { &opcode_nop, &opcode_set, &opcode_and, &opcode_or, &opcode_add, &opcode_sub, &opcode_shl, &opcode_shr, &opcode_jmp, &opcode_prt };
答案 0 :(得分:2)
鉴于register_ptr
的声明,行:
*register_ptr[i] = *(int*)register_ptr[j];
}
else
{
*register_ptr[i] = *(int*)(atoi(arg2));
都是错的(一个是无害的,一个是无害的)。第一个不需要演员;你写得很好:
*register_ptr[i] = *register_ptr[j];
第二个真的不需要任何转换,但它也不需要间接级别:
*register_ptr[i] = atoi(arg2);
这会将atoi(arg2)
返回的整数分配给register_ptr[i]
所指向的内存,该内存可能是REGA
,REGB
,REGC
或{ {1}}。如上所述,您将REGX
中的值视为模拟器内存空间中的地址并读取其中的值,以及各种(可能)不需要的后果(例如核心转储)。