【C语言】结构体传递给函数的方式的应用
一般,将结构体传递给函数的方式有如下3种:
1. 用结构体的单个成员作为函数参数,向函数传递结构体的单个成员(属于传值调用,不会影响相应的实参结构体的值)
2. 用结构体变量做函数参数,向函数传递结构体完整结构(属于传值调用,不会影响相应的实参结构体的值)
3. 用结构体指针或结构体数组作函数参数属于按引用调用,会影响相应的实参结构体的值,向函数传递结构体地址,因为仅复制结构体首地址一个值给被调函数,相对于第二种方式,这种传递效率更高
通过结构体存储十个员工的个人信息,在通过冒泡排序对其工龄进行排序,最后输出:
(1)
#include <stdio.h>
#define N 4
struct worker
{
char num[7];
char name[11];
int year;
int salary;
};
void Sort(struct worker *p, int n);
int main(void)
{
struct worker work[N];
int i;
for ( i = 0; i < N; i++ )
{
printf("请输入第%d个工人信息:", i+1);
scanf("%s%s%d%d", work[i].num, work[i].name, &work[i].year, &work[i].salary);
}
Sort(work,N);
printf("n依大到小输出工人的信息:n");
for ( i = 0; i < N; i++ )
{
printf("编号:%s,姓名:%s,工龄:%d,工资:%dn",
work[i].num, work[i].name, work[i].year, work[i].salary);
}
return 0;
}
void Sort(struct worker *p, int n)
{
int i, j;
struct worker temp;
for ( i = 0; i < n-1; i++ )
{
for ( j = 0; j < n-i-1; j++ )
{
if ( p[j].year < p[j+1].year )
{
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}
}
(2)
#include <stdio.h>
#define N 4
struct worker
{
char num[7];
char name[11];
int year;
int salary;
};
void Input(struct worker *p);
void Sort(struct worker *p, int n);
void Print(struct worker *p);
int main(void)
{
struct worker work[N];
int i;
Input(work);
Sort(work,N);
Print(work);
return 0;
}
void Input(struct worker *p)
{
for ( int i = 0; i < N; i++ )
{
printf("请输入第%d个工人信息:", i+1);
scanf("%s%s%d%d", p[i].num, p[i].name, &p[i].year, &p[i].salary);
}
}
void Print(struct worker *p)
{
printf("n依大到小输出工人的信息:n");
for ( int i = 0; i < N; i++ )
{
printf("编号:%s,姓名:%s,工龄:%d,工资:%dn",
(p+i)->num, (p+i)->name, (p+i)->year, (p+i)->salary);
}
}
void Sort(struct worker *p, int n)
{
int i, j;
struct worker temp;
for ( i = 0; i < n-1; i++ )
{
for ( j = 0; j < n-i-1; j++ )
{
if ( p[j].year < p[j+1].year )
{
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}
}
(3)
基于(2)将(2)中的主函数模块更改:
int main(void)
{
struct worker work;
Input(&work);
Sort(&work,N);
Print(&work);
return 0;
}