先来回顾一下经典`
#include<stdio.h>
void fq2(int a);
int main()
{
int a=10;
fq2(a);
printf("%d\n",a);
}
void fq2(int a)
{
a=15;
}
很显然该程序的运行结果还是10,不会受到函数的影响,我们一般处理这个问题的方法是传递一个地址过去,这样就可以直接做修改了。
当然我们也可以换一种思路,我们直接转递一个返回值出来,去接一个整体的函数值。
#include<stdio.h>
void fq2(int a);
int fq3(int b);
int main()
{
int a=10;
fq2(a);
printf("%d\n",a);
//传递返回值
a=fq3(a);
printf("%d\n",a);
printf("%d\n",fq3(a));//函数的值
}
void fq2(int a)
{
a=15;
}
int fq3(int b)
{
b=15;
return b;
}
我们把函数的返回值传出来,然后用a去接这个值,可以变相的达到这种效果即a=fq3(a);(注意fq3(a);里面不要写成形参fq3(b);b在主函数中并未定义,这是经常会犯的一个错误),此时的a就为函数fq3的值,可以顺便打印一下,该函数的值方便看一下。
在这里可以清楚的看到a的改变
我们再来看一道程序
#include<stdio.h>
struct n{
int x;
char c;
};
void func(struct n b);
int main()
{
struct n a={10,'x'};
func(a);
printf("%d,%c\n",a.x,a.c);
}
void func(struct n b)
{
b.x=20;
b.c='y';
}
很显然这道题的运行结果也是 10,‘x’;
问题同上,同样我们可以通过结构体类型指针,讲地址传进去,不过我们仍然可以利用返回值,讲函数的值给它搞出来。
#include<stdio.h>
struct n{
int x;
char c;
};
void func(struct n b);
struct n func2(struct n b);
int main()
{
struct n temp={0};//定义一个结构体去承接结构体类型的函数
struct n a={10,'x'};
func(a);
printf("%d,%c\n",a.x,a.c);
temp=func2(a); //对其结构体内部的成员进行打印
printf("%d,%c\n",temp.x,temp.c);
}
void func(struct n b)
{
b.x=20;
b.c='y';
}
struct n func2(struct n b)
{
b.x=20;
b.c='y';
return b;
}
这样就可以得到想要的结果
当然了,为了体现是对a进行操作的,我们可以不用中间结构体变量去接返回值,而是直接用a去对接,即
a=func2(a);
printf("%d,%c\n",a.x,a.c);
这样也是可以的
一些常见的小错误
我们在进行函数调用的时候经常会因为各种疏漏造成各种小错误。
比如下面
1、这里忘记进行函数值返回了,那么前面写的再好,函数的值传递不出来也没有用。
struct n func2(struct n b)
{
b.x=20;
b.c='y';
//return b;
}
如图,输出不到想要的结果
struct n func(struct n b1)
{
b1.x=20;
b1.c='y';
return b1.x; //这个就不行,因为这个是一个int型,不是struct n的类型
//return b1;
这也是一种返回值错误,会报返回类型不一致的错误
error: incompatible types when returning type ‘int’ but ‘struct n’ was expected
这里就是将结构体内一个成员变量误当成整个结构体类型了
2、在函数调用的时候,有时候会报这种错误,即两边的类型不一致,在经常CV大法的时候,喜欢下面定义好的函数直接复制上来,要不就是缺斤少两,要不就是连带函数类型也复制上来了,会导致各种报错,如下
error: incompatible types when assigning to type ‘struct n’ from type ‘struct n (*)(struct n)’
temp=func2;
这种类型不一致,是右边函数格式书写错误,没有把参数带上正确的应该是
temp=func2(a);而非temp=func2;
或者像这种
error: expected expression before ‘struct’
temp=func2(struct n b)
这种就是将函数参数类型也带上了,函数调用是不用写函数类型的,
在自定义的函数类型中,部分编译器不会把自己定义的函数类型变色,导致经常会不注意这种情形。