我是C編程的新手,我正在學習通過值傳遞一個結構作爲參數作爲參數(作爲我的課程的一部分) 。我用gcc 4.6.3版本在Ubuntu Linux 12.04LTS 以下是這似乎邏輯和語法正確的源代碼(對我來說),但在編譯時我得到的錯誤:通過作爲參數傳遞結構作爲參數錯誤在海灣合作委員會版本4.6.3
#include<stdio.h>
struct sal {
char name[30];
int no_of_days_worked;
int daily_wage;
};
typedef struct sal Sal;
void main()
{
Sal salary;
int amount_payable;
salary=get_data(salary); //Passing struct as function arguments
printf("\nThe name of the Employee is %s",salary.name);
printf("\nNumber of days worked is %d",salary.no_of_days_worked);
printf("\nThe daily wage of the employees is %d",salary.daily_wage);
amount_payable=wages(salary);
printf("\nThe amount payable to %s is %d",salary.name,amount_payable);
}
Sal get_data(Sal income)
{
printf("\nEnter the name of the Employee: \n");
scanf("%s",&income.name);
printf("\nEnter the number of days worked:\n");
scanf("%d",&income.no_of_days_worked);
printf("\nEnter the employee daily wages:\n");
scanf("%d",&income.daily_wage);
return(income); //Return back a struct data type
}
int wages(Sal x)
{
int total_salary;
total_salary=x.no_of_days_worked*x.daily_wage;
return(total_salary);
}
在編譯代碼我得到以下錯誤:
struct_to_function.c: In function ‘main’:
struct_to_function.c:15:7: error: incompatible types when assigning to type ‘Sal’ from type ‘int’
struct_to_function.c: At top level:
struct_to_function.c:22:5: error: conflicting types for ‘get_data’
struct_to_function.c:15:8: note: previous implicit declaration of ‘get_data’ was here
struct_to_function.c: In function ‘get_data’:
struct_to_function.c:25:1: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[30]’ [-Wformat]
我認爲它的編譯器是否使用堆棧或寄存器有一些事情與gcc編譯器執行或執行計劃。再次,這些只是我的業餘假設。
人間 「和income.name);」最好是「scanf(」%s「,income.name);」因爲數組本身衰減爲一個指向其第一個元素的指針,即char *。儘管結果應該具有相同的數值,即獲得數組的地址,但是嚴格地說是類型錯誤,即scanf應該起作用。只是不要增加指針;-)。 –