2017-12-18 174 views
0

所以我有這樣的結構:指針如何與預定義的結構進行交互?

struct state { 
    int previous[2]; 
    int current[2]; 
    bool pen; 
}; 
typedef struct state state; 

在我使用這個作爲一個參數的一些功能,例如:

void new_state(&s, char *file, int i, int j){ 
    int new = s -> current[j]; 
    s -> current[j] = operand(byte(i, file)) + s -> current[j]; 
    s -> previous[j] = new; 
} 

我在一個函數調用這些,其中I定義S作爲前「預期的聲明說明符或「...」:從狀態:

void main_function(char *file){ 
    state s; 
    display *display = newDisplay(file, 200, 200); 
    int j = size(file); 
    for(int i=0; i<j; i++){ 
    if(opcode(byte(i, file)) == 0){ 
     new_state(&s, file, i, 0); 
    } 
    else if(opcode(byte(i, file)) == 1){ 
     new_state(&s, file, i, 1); 
     draw(s, display, file); 
    } 
    else if(opcode(byte(i, file)) == 2){ 
     pause(display, operand(byte(i, file)) * 10); 
    } 
    else{ 
     new_pen(s); 
    } 
    end(display); 
} 
} 

但是,編譯我仍然得到錯誤消息時'令牌,但我不明白爲什麼。我已經將變量s定義爲結構狀態的一部分,然後通過使用& s,這給它的地址是正確的嗎?

+2

你得到它,因爲'無效NEW_STATE(&S,字符*文件,詮釋我,詮釋J)'完成胡言亂語。函數聲明不是函數調用。 – Lundin

+0

請注意,點'.'和箭頭' - >'運算符確實非常緊密,並且不應該在它們周圍有空格,而不像像''這樣的低優先級二元運算符,它們周圍應該有空格。是的,這是風格。除了新手代碼外,點和箭頭周圍的空格絕對不常見。 –

回答

1

void new_state(&s,是錯誤的。

在C應改爲

void new_state(state *s, char *file, int i, int j) 
+0

它不是C/C++的混合體,因爲調用函數時傳入的內容確實是一個地址。這只是一個不正確的函數參數聲明。 –

+0

@SergeBallesta,是;固定的。 –

+0

在調用'new_state()'函數時使用'&s'作爲第一個參數 – EsmaeelE

0

您必須函數定義和函數調用進行區分。使用參數定義函數時,必須提供每個參數的數據類型,除非它是可變參數列表...

但是,在調用該函數時,應該傳遞一個常量或兼容類型的變量。

0
void new_state(&s, char *file, int i, int j){ 
    int new = s -> current[j]; 
    s -> current[j] = operand(byte(i, file)) + s -> current[j]; 
    s -> previous[j] = new; 
} 

這是你的代碼中的函數定義。 struct state是一種數據類型。 s只是struct state類型的變量。還有&s(在s定義的範圍內)是指存儲器中s的地址。

你真正想在這裏做的是使指針指向任何類型爲struct state的變量。對於正確的語法將

void new_state(struct state * s, char * file, int i, int j){ 
    ...(function body)... 
} 

現在,在函數調用,(當你在主或其他地方使用的函數的)。你有點放了你已經做過的東西來使用。

該聲明是通用的(用於任何輸入)。該電話是特定的(或特定的)。

這裏您指定的參數(或arguments)您是passing的函數。

這是調用會是什麼樣子

. 
. 
. 
new_state(&s, file, i, j); 
. 
.