2014-12-04 98 views
0

我想做一些簡單的事情,只需將參數傳遞給一個函數,但我似乎遇到了很多麻煩,我似乎無法弄清楚如何解決它。僅供參考這是一個家庭作業,將成爲一個基本的彙編語言模擬器。在函數中與參數衝突的類型C

下面是代碼

char cmd_char; 
char leadChar; 
int location; 
short int value; 

words_read = sscanf(cmd_buffer, "%d %c%hx x%hx", &cmd_char, &leadChar, &location, &value); 

... 

done = execute_command(cmd_char, cpu, leadChar, location, value); 

... 

int execute_command(char cmd_char, CPU *cpu, char leadChar, int location, int value) 
{ 
    ... 
} 

的字符串被輸入到的sscanf(...)要麼是:

m x305f x002c 
r r6 x10a5 
r r3 x0014 
j x3030 

沒有與掃描正確的價值觀沒有問題,但是當我將變量leadChar,位置和值作爲參數添加到execute_command,我一直無法成功調用它。看到下面的錯誤。

的錯誤信息

Lab10.c:42:46: error: expected declaration specifiers or '...' be         fore '(' token 
int execute_command(char cmd_char, CPU *cpu, (char) void, (int) void, (int) voi         d); 
              ^
Lab10.c:42:59: error: expected declaration specifiers or '...' be         fore '(' token 
int execute_command(char cmd_char, CPU *cpu, (char) void, (int) void, (int) voi         d); 

Lab10.c:277:5: error: conflicting types for 'execute_command' 
int execute_command(char cmd_char, CPU *cpu, char leadChar, int location, int v         alue) 
    ^
Lab10.c:278:1: note: an argument type that has a default promotio         n can't match an empty parameter name list declaration 
{ 
^ 
Lab10.c:265:20: note: previous implicit declaration of 'execute_c         ommand' was here 
      done = execute_command(cmd_char, cpu, leadChar, location, value); 
        ^
                ^
Lab10_BenShaughnessy.c:42:71: error: expected declaration specifiers or '...' be         fore '(' token 
int execute_command(char cmd_char, CPU *cpu, (char) void, (int) void, (int) voi         d); 
+0

你的函數聲明是否符合你的定義? – Gopi 2014-12-04 05:30:54

+0

在首次使用或包含適當的頭文件之前聲明'int execute_command(char cmd_char,CPU * cpu,char leadChar,int位置,int值);' – 2014-12-04 05:32:23

回答

1

在行:

words_read = sscanf(cmd_buffer, "%d %c%hx x%hx", &cmd_char, &leadChar, &location, &value); 

你告訴sscanf()&locationshort *,但它不是;它是一個int *。您需要將轉換規格更改爲%x。海灣合作委員會應該告訴你這個問題,儘管你可能需要輕輕地扭動它的手臂(建議使用-Wall;如果你不使用它,則需要使用IIRC,-Wformat,但是-Wall更好)。

事實上,作爲chux指出在comment,這裏還有%d&cmd_char之間的類型不匹配了。因此,你真正需要的:

words_read = sscanf(cmd_buffer, "%c %c%d x%hx", &cmd_char, &leadChar, &location, &value); 

如果你不知道是否有可能在該字符串開頭的空格,然後第一%c前添加一個空格。請注意,即使你寫的格式字符串的空間,sscanf()對待,作爲可選的白色空間,所以格式將接受這兩種:各種其他輸入太

m x305f x002c 
mx305fx002c 

和。

+1

懷疑''%d ...「'應該是''%c ...」'也 – chux 2014-12-04 05:42:49

+0

@chux:yup,我同意。 – 2014-12-04 05:43:50

+0

...或者「%c ...」(帶有空格) – chux 2014-12-04 05:45:24