2013-11-01 55 views
1

當我試圖編譯此代碼時,出現錯誤:轉換爲非標量類型請求。此錯誤涉及行:請求的非標量類型C

func(record); 

我可以知道我的代碼中出了什麼問題嗎?

#include <stdio.h> 
#include <string.h> 

struct student 
{ 
int id; 
char name[30]; 
float percentage; 
}; 
void func(struct student record); 

int main() 
{ 

struct student record[2]; 
func(record); 
return 0; 
}  

void func(struct student record[]) { 
int i; 
record[0].id=1; 
strcpy(record[0].name, "lembu"); 
record[0].percentage = 86.5; 


record[1].id=2; 
strcpy(record[1].name, "ikan"); 
record[1].percentage = 90.5; 


record[2].id=3; 
strcpy(record[2].name, "durian"); 
record[2].percentage = 81.5; 

for(i=0; i<3; i++) 
{ 
    printf("  Records of STUDENT : %d \n", i+1); 
    printf(" Id is: %d \n", record[i].id); 
    printf(" Name is: %s \n", record[i].name); 
    printf(" Percentage is: %f\n\n",record[i].percentage); 
} 

} 
+0

修正你的函數聲明,它應該包括'[]'如果你傳遞的記錄數組。 –

回答

1

你的原型func說:

void func(struct student record); 

它應該是:

void func(struct student record[]); 
1

這是因爲你有衝突的函數聲明。

void func(struct student record[]) 

相當於

void func(struct student * record) 

但你最初的宣言是

void func(struct student record); 
1

當你宣佈你做的功能,所以像:

void func(struct student record); 

但是當你去使用它,你傳遞一個

struct student record[2]; 

雖然你在爲

void func(struct student record[]) { 

到那個時候已經太晚了定義,編譯器會不顧稍後的定義聲明。

添加[]的聲明:

void func(struct student record[]); 
0

我做了一些改變

void func(struct student record[]); 

int main() 
{ 
    struct student record[3]; 

的完整代碼:

#include <stdio.h> 
#include <string.h> 

struct student 
{ 
    int id; 
    char name[30]; 
    float percentage; 
    }; 
void func(struct student record[]); 

int main() 
{ 
    struct student record[3]; 
    func(record); 
    return 0; 
}  

void func(struct student record[]) { 
    int i; 
    record[0].id=1; 
    strcpy(record[0].name, "lembu"); 
    record[0].percentage = 86.5; 


    record[1].id=2; 
    strcpy(record[1].name, "ikan"); 
     record[1].percentage = 90.5; 


     record[2].id=3; 
     strcpy(record[2].name, "durian"); 
     record[2].percentage = 81.5; 

     for(i=0; i<3; i++) 
     { 
      printf("  Records of STUDENT : %d \n", i+1); 
      printf(" Id is: %d \n", record[i].id); 
      printf(" Name is: %s \n", record[i].name); 
      printf(" Percentage is: %f\n\n",record[i].percentage); 
     } 

} 
0

錯誤發生,因爲這樣做的func實際和形式參數的匹配時,編譯器不能轉換從student *student

在函數原型的參數都被定義爲student類型。在定義中,它被聲明爲一個數組,它在C中衰減爲一個指針。

修復的函數原型,使其聲明正是你想要的:

void func(struct student record[]); 
相關問題