0

我正在尝试构建一个简单的程序集模拟器。我正在尝试创建 set 函数;该函数将采用 2 个参数(字符串数组)arg1 和 arg2。然后它将字符串与字符串数组进行比较,字符串数组是函数指针数组列表的索引。

我遇到的问题是当我尝试设置寄存器的值时。我尝试了该行的许多变体:

*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 和 register_ptr 的声明:

 const char *register_str[] = {"REGA", "REGB", "REGC", "REGX"};
 int *register_ptr[]={&REGA, &REGB, &REGC, &REGX};

我使用两个数组来决定哪个操作码、一个字符串数组和一个函数指针数组,我通过字符串索引并使用相同的索引位置来调用函数:

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 };
4

1 回答 1

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、或之一。正如所写的,您将 in 的值视为模拟器内存​​空间中的地址并读取那里的值,并带来各种(可能)不需要的后果(例如核心转储)。REGBREGCREGXarg2

于 2013-05-08T23:30:10.657 回答