2013-03-04 135 views
0

我正在開發一個項目,並試圖將一個結構傳遞給一個函數,我嘗試了各種方法,但即時通訊仍然很短。我得到錯誤信息:將結構傳遞給Visual Studio中的函數

非法使用這種類型的表達式。

真的很感謝你的幫助。

#include <stdio.h> 
    #include <stdlib.h> 
    #include <time.h> 

struct big{ 
     int day; 
     int year; 
     char month[10]; 
     } ; 

     void gen(struct big); 
     void main() 
    { 
int choice; 

printf("\t\t\t\t\t*MENU*\n\n\n"); 
printf("\t\tGenerate Buying/Selling Price-------------------PRESS 1\n\n"); 
printf("\t\tDisplay Foreign Exchange Summary----------------PRESS 2\n\n"); 
printf("\t\tBuy Foreign Exchange----------------------------PRESS 3\n\n"); 
printf("\t\tSell Foreign Exchange---------------------------PRESS 4\n\n"); 
printf("\t\tExit--------------------------------------------PRESS 5\n\n\n\n"); 
printf("\t\tPlease enter your choice"); 
scanf("%d", &choice); 

if (choice == 1) 
{ 
    gen(big); 
} 
system("pause"); 

    } 

void gen(big rec) 
{ 
printf("Enter the date in the format: 01-Jan-1993"); 
scanf("%d %s %d", &rec.day, &rec.month, &rec.year); 
} 
+0

'void main'是未定義的行爲。 – chris 2013-03-04 02:10:00

回答

2

您試圖傳遞結構定義本身,創建它的一個實例,然後通過它。

big myBig; 
gen(myBig); 
+0

非常感謝Baris。有用。我很想有一個詳細的解釋,所以我可以理解爲什麼它在我創建某種形式的變量時起作用,例如:myBig from big,然後在函數調用中使用myBig。我沒有真正明白你的意思創建一個實例。 – 2013-03-04 02:22:28

+0

零件struct big {}只是結構的定義。你不能像變量那樣使用'big'這個名字。 'big'是一個類似'int'的類型。首先你需要創建一個類型爲「big」的變量,然後你可以使用它。一個實例只是某種類型的變量。 – 2013-03-04 02:26:00

+0

謝謝。絕對清除問題 – 2013-03-04 02:39:28

0

a>您不會創建結構爲big的對象。你可以用big obj;

b>void main是一種不好的編程方式。至少使用int main(void)

C>傳遞堆棧

這樣的引用,而不是一個副本:

void gen(big& obj) 
{ 
    printf("Enter the date in the format: 01-Jan-1993"); 
    scanf("%d %s %d", &rec.day, &rec.month, &rec.year); 
} 

你必須創建big類型的對象。 struct big只是一個房子的藍圖。而bigObject以下的房子。 struct big類型的實際變量HOLDS值等。

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

struct big{ 
    int day; 
    int year; 
    char month[10]; 
}; 

void gen(struct big); 
void main() 
{ 
    int choice; 
    big bigObject; 
    printf("\t\t\t\t\t*MENU*\n\n\n"); 
    printf("\t\tGenerate Buying/Selling Price-------------------PRESS 1\n\n"); 
    printf("\t\tDisplay Foreign Exchange Summary----------------PRESS 2\n\n"); 
    printf("\t\tBuy Foreign Exchange----------------------------PRESS 3\n\n"); 
    printf("\t\tSell Foreign Exchange---------------------------PRESS 4\n\n"); 
    printf("\t\tExit--------------------------------------------PRESS 5\n\n\n\n"); 
    printf("\t\tPlease enter your choice"); 
    scanf("%d", &choice); 

    if (choice == 1) 
    { 
     gen(bigObject); /*pass bigObject to gen*/ 
    } 
    system("pause"); 
    return 0; 
} 

void gen(big& rec) 
{ 
    printf("Enter the date in the format: 01-Jan-1993"); 
    scanf("%d %s %d", &rec.day, &rec.month, &rec.year); 
} 
+0

謝謝。這一個是方法是新的,即時通訊試圖瞭解它 – 2013-03-04 02:38:41

+0

沒有什麼太多了。你用'struct'創建了一個類型,現在你需要定義一個該類型的變量。代碼中的'big'是一種類型。 'bigObject'是變量。 – 2013-03-04 02:41:43

+0

我現在正在意識到這一點。最好通過引用傳遞它似乎允許更好的模塊化。我想使用指針應該做的竅門 – 2013-03-04 02:53:08