| |
我们知道,C语言的精髓是函数的作用。因此,C语言支持把结构值作为参数传递给函数是很自然的。要把结构体的值从一个函数体传递给另一个函数,有以下3种方法。
(1) 把结构体的每个成员作为函数调用的实参进行传递。然后就可以像普通变量一样来处理实参。这是最基本的方法,但如果结构体很大,这种方法就变得难以控制,效率也不高。
(2) 将整个结构体的副本传递给被调用函数。由于函数使用的是结构体的副本,因此,在函数中对结构体成员的任何改变不能反映到初始结构体中。因此,需要函数将整个结构体返回给调用函数。但并不是所有编译器都支持这种方法。
(3) 使用指针以参数形式来传递结构体。在这种情况下,结构体的地址传递给被调用函数。该函数可以间接地访问整个结构体。这类似于将数组传递给函数。与第二种方法相比,这种方法更有效。
将结构体的副本传递给函数的一般形式为:
struct book_bank,book1,book2,book3;
被调用函数的形式如下:
function_name(structure_variable_name);
data_type function_name(struct_type st_name)
{
......
return(expression);
}
注意一下一些要点:
(1) 被调用函数必须声明为与返回值相适应的数据类型。例如,如果返回整个结构体的副本,那么必须声明为struct加上恰当的标记符名。
(2) 被调用函数中用作实参的结构体变量和相应形参必须为相同的结构体类型。
(3) 当被调用函数要返回数据给调用函数时,才需要return语句。其表达式可以是任意简单的变量、结构体变量或使用简单变量的表达式。
(4) 当函数返回的是一个结构体时,必须将它赋给调用函数中的相同类型的结构体。
(5) 必须在调用函数中恰当地声明被调用函数。
编写一个程序,演示将整个结构体作为一个参数传递给函数。
struct stores
{
char name[20];
float price;
int quantity;
}
struct stores update(struct stores product,float p,int q);
float mul(struct stores stock);
main()
{
float p_increment,value;
int q_increment;
struct stores item={"XYZ",25.75,12};
printf("\nInput increment values:");
printf("price increment and quantity increment\n");
scanf("%f %d,&p_increment,&q_increment");
item=update(item,p_increment,q_increment);
printf("Update values of item\n\n");
printf("Name :%s\n",item.name);
printf("Price :%s\n",item.price);
printf("Quantity :%s\n",item.quantity);
value=mul(item);
printf("\nValue of item=%f\n",value);
}
struct stores update(struct stores product,float p,int q)
{
product.price+=p;
product.quantity+=q;
return(product);
}
float mul(struct stores stock)
{
return(stock.price*stock.quantity);
}
凌阳教育,全国唯一一家原厂式嵌入式培训机构,专业从事嵌入式人才培训13年,最近新开课程信息安全工程师培训,想了解更多嵌入式资料下载或者是凌阳教育的动态,请访问凌阳教育官网www.sunplusedu.com。