前言

如果对结构体变量的使用不太熟悉,可以先看看博主的这篇文章【C语言】结构体变量定义、初始化、使用

 

首先声明结构体类型,注意,若要跨函数使用结构体,结构体类型的声明必须在函数外部:

struct students
{
	char name[20];
	int age;
};

然后初始化结构体变量及指向结构体变量的指针:

struct students stu1={"Allen",18},*pstu;
pstu=&stu1;

 

方法 1  结构体变量作为参数

函数体:

// 1 用结构体变量作函数参数
void printStu(struct students stu)
{
	printf("%s    %d\n\n",stu.name,stu.age);
}

 

方法 2  结构体变量的成员作参数

函数体:

// 2 用结构体变量的成员作函数参数
void printStu2(char name[20],int age)
{
	printf("%s    %d\n\n",name,age);
}

 

方法 3  用指向结构体变量(或结构体数组)的指针作为参数

函数体:

// 3 用指向结构体变量(或结构体数组)的指针作为参数
void printStu3(struct students *pstu)
{
	printf("%s    %d\n\n",pstu->name,pstu->age);
}

 

附录

完整测试代码如下:

#include <stdio.h>
#include <string.h>

//声明结构体类型(若要跨函数使用,必须定义在外部)
struct students
{
	char name[20];
	int age;
};

int main()
{
    //定义并初始化结构体变量及指针
	struct students stu1={"Allen",18},*pstu;
	pstu=&stu1;

	//函数声明
	void printStu(struct students);
	void printStu2(char [20],int);
	void printStu3(struct students *);

	//调用
	printf("姓名    年龄\n\n");
	printStu(stu1);
	printStu2(stu1.name,stu1.age);
	printStu3(pstu);
	return 0;
}

//函数定义

// 1 用结构体变量作函数参数
void printStu(struct students stu)
{
	printf("%s    %d\n\n",stu.name,stu.age);
}

// 2 用结构体变量的成员作函数参数
void printStu2(char name[20],int age)
{
	printf("%s    %d\n\n",name,age);
}

// 3 用指向结构体变量(或结构体数组)的指针作为参数
void printStu3(struct students *pstu)
{
	printf("%s    %d\n\n",pstu->name,pstu->age);
}

结果:

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐