2012-09-22 72 views
0

我已經在一個練習中難過了幾個小時,我必須使用函數在結構中構建一個數組並打印它。在我目前的程序中,它編譯但運行時崩潰。從結構中打印陣列

#define LIM 10 

typedef char letters[LIM]; 

typedef struct { 
    int counter; 
    letters words[LIM]; 
} foo; 


int main(int argc, char **argv){ 
    foo apara; 
    structtest(apara, LIM); 
     print_struct(apara); 

} 

int structtest(foo *p, int limit){ 
    p->counter = 0; 
    int i =0; 
    for(i; i< limit ;i++){ 
     strcpy(p->words[p->counter], "x"); 
       //only filling arrays with 'x' as an example 
     p->counter ++; 
    } 
    return; 

我確實認爲這是由於我錯誤的使用/指針組合。我試着調整它們,但產生的任何「不兼容的類型」錯誤,或數組是看似空白

} 

void print_struct(foo p){ 
    printf(p.words); 

} 

我還沒有做出它成功地達到了print_struct階段,但我不能確定是否p.words是要調用的正確項目。在輸出中,我希望函數返回一個x的數組。 如果我犯了某種嚴重的「我應該已經知道這個」C錯誤,我很抱歉。謝謝你的幫助。

+0

我也不會的結構,因爲要複製的sizeof(富)堆棧傳遞給'print_struct'。請傳遞一個指針。 – Kludas

回答

1

structest()的第一個參數被聲明爲foo類型的指針。

int structtest(foo *p, int limit) 

主要是,你沒有傳遞一個指向foo變量的指針,你只是傳遞一個foo變量。

structtest(apara, LIM); 

嘗試指針傳遞到一個Foo變量是這樣的:

structtest(&apara, LIM); 
0
void print_struct(foo p){ 
    printf(p.words); 

} 

我還沒有做出它成功地達到了print_struct階段,但我不確定 是否p.words是要調用的正確項目。在 輸出中,我希望函數返回一個x的數組。我提前道歉,如果我犯了某種嚴重的「我應該 已經知道這個」C錯誤。謝謝你的幫助。

您不能將數組發送到printf,您可以使用其他語言打印數組的方式。您必須自己循環:

void print_struct(foo paragraph) 
{ 
    printf("counter: %d\n",paragraph.counter); 
    for (int i = 0; i < paragraph.counter; i++) 
    { 
     printf("words[%d] %s\n",i,paragraph.words[i]); 
    } 
} 

您應該將main()函數移動到源代碼的底部。或者,你必須添加函數原型低於主定義的任何代碼,上述主:

int structtest(foo *p, int limit); 
.... 
main() 
{ 
... 
} 
int structtest(foo *p, int limit) 
{ 
... 
}