gpt4 book ai didi

c - 在 gcc ver 4.6.3 中按值将 Struct 作为参数传递给函数时出错

转载 作者:太空宇宙 更新时间:2023-11-04 11:12:39 24 4
gpt4 key购买 nike

我是 C 编程的新手,我正在学习将结构作为参数按值传递给函数(作为我类(class)的一部分)。我在 Ubuntu Linux 12.04LTS 上使用 gcc ver 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编译器是用栈还是寄存器,跟实现或者执行计划有关系。同样,这些只是我的业余假设。

最佳答案

当 C 编译器遇到从 main 调用 get_data 时,它不知道返回类型是什么(因为它既没有看到函数声明也没有看到函数定义),因此它假定为 int。这会给您第一个警告,因为 salary 与赋值中的 int 不兼容。编译器继续运行,现在认为 get_data 返回 int,然后在遇到 get_data 的实际定义时会报错。

您应该在 main 之前添加一个函数原型(prototype),或者确保函数总是在调用之前定义(通过重新排列它们在源代码中的顺序)。

最后一个警告是因为带有 %s 说明符的 scanf 需要一个 char*,但你给了它一些类型 字符 (*)[30]。传递数组时不要使用 &

只需在 main 之前添加以下内容:

Sal get_data(Sal income);
int wages(Sal x);

关于c - 在 gcc ver 4.6.3 中按值将 Struct 作为参数传递给函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22364833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com