Linux C 编程教程第 26 部分 - 结构和函数
在此页
- C 编程语言中的结构和函数
- 结论
在我们之前的一个命令行教程中,我们谈到了结构的概念。使用易于理解的示例,我们讨论了基本内容,例如什么是结构以及为什么需要它们。以此为基础,在本教程中,我们将讨论如何一起使用结构和函数。
C 语言中的结构和函数
在开始之前,让我们快速回顾一下结构的声明方式。这是一个例子:
struct emp_details {
int emp_code;
int emp_age;
};
所以在这里,struct 关键字——如果你在 C 中定义一个结构,这是强制性的——表示声明的开始。它后面跟着一个标签,或者你可以说出结构的名称。然后,在方括号内,您有两个整型变量,它们组合在一起作为此结构的一部分。
要使用这个结构,首先需要定义它的实例或对象。您可以通过以下方式执行此操作:
emp_details obj;
然后可以通过以下方式访问结构成员:
obj.emp_code
obj.emp_age
现在,谈到函数,函数可以返回结构,也可以接受参数形式的结构。这是一个例子:
#include <stdio.h>
struct emp_details {
int emp_code;
int emp_age;
};
struct emp_details fill(int code, int age)
{
struct emp_details obj;
obj.emp_code = code;
obj.emp_age = age;
return obj;
}
int main()
{
int x,y;
printf("Enter employee code: ");
scanf("%d", &x);
printf("\n Enter employee age: ");
scanf("%d", &y);
struct emp_details new_obj;
new_obj = fill(x,y);
printf("\n The employee code and age you entered are: %d and %d", new_obj.emp_code, new_obj.emp_age);
return 0;
}
所以在这里,在这个例子中,我们有一个 fill 函数,它接受两个整数,将它们视为代码和年龄,根据这些信息填充一个结构,然后按值将结构返回给函数的调用者。
现在,正如我之前在上面的声明中提到的,结构也可以作为函数参数传递。以下是一个示例,其中函数 fill 接受 emp_details 结构作为参数。
#include <stdio.h>
struct emp_details {
int emp_code;
int emp_age;
};
void fill(struct emp_details obj)
{
printf("\n The employee code and age you entered are: %d and %d", obj.emp_code, obj.emp_age);
}
int main()
{
int x,y;
printf("Enter employee code: ");
scanf("%d", &x);
printf("\n Enter employee age: ");
scanf("%d", &y);
struct emp_details new_obj;
new_obj.emp_code = x;
new_obj.emp_age = y;
fill(new_obj);
return 0;
}
在我的案例中,这是输出:
Enter employee code: 36
Enter employee age: 29
The employee code and age you entered are: 36 and 29
继续,像普通变量、数组等,也可以有指向结构的指针。这是一个例子:
struct emp_details *ptr;
与往常一样,指针在结构大小很大的情况下派上用场,并且您将其作为参数发送给函数。理想情况下,您可以通过指针对象访问结构变量:
(*ptr).emp_code
(*ptr).emp_age
但是为了简单起见,C 允许您省略 * 和 .并使用 -> 代替。下面是一个例子:
ptr->emp_code
ptr->emp_age
这是一个使用结构指针的示例:
#include <stdio.h>
struct emp_details {
int emp_code;
int emp_age;
};
void fill(struct emp_details *obj)
{
printf("\n The employee code and age you entered are: %d and %d", obj->emp_code, obj->emp_age);
}
int main()
{
int x,y;
printf("Enter employee code: ");
scanf("%d", &x);
printf("\n Enter employee age: ");
scanf("%d", &y);
struct emp_details new_obj;
new_obj.emp_code = x;
new_obj.emp_age = y;
fill(&new_obj);
return 0;
}
虽然这与我们之前使用的示例相同,但更改 - 因为我们现在使用结构指针 - 以粗体突出显示。
结论
在本教程中,我们通过讨论如何一起使用函数和结构来扩展我们对结构的理解。我们鼓励您在本地系统上尝试我们在此处使用的示例。如有任何疑问或疑问,请在下方发表评论。