我正在嘗試構建一個簡單的程序集模擬器。 我想創建設置功能;該函數將採用2個參數(字符串數組)arg1 & arg2。 然後它將比較字符串與字符串數組,這是函數指針數組列表的索引。嘗試將int傳遞到指針時發生總線錯誤
我遇到的問題是當我嘗試設置寄存器的值。 我已經嘗試了很多變種的線路:
*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[]={®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 };
arg2究竟是什麼?這是一個有效的內存地址來讀取一個int? – 2013-05-08 23:06:59
你確定你不是指'register_ptr [i] =(int *)(atoi(arg2));'? – 2013-05-08 23:08:38
arg2將是一個字符串,具有常數(數字)或寄存器(REGA,REGB,REGC,REGX)。我不明白你的意思你的第二個問題 – Babbleshack 2013-05-08 23:09:42