向函数传递结构指针

作者:追风剑情 发布于:2020-1-20 14:04 分类:C

示例1: 传递结构体指针

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>

#define NLEN 30

struct namect {
	char fname[NLEN];
	char lname[NLEN];
	int letters;
};

char* s_gets(char* st, int n);
void getinfo(struct namect*);
void makeinfo(struct namect*);
void showinfo(const struct namect*);

int main(int argc, char* argv[])
{
	struct namect person;

	getinfo(&person);
	makeinfo(&person);
	showinfo(&person);

	system("pause");
	return 0;
}

void getinfo(struct namect* pst)
{
	printf("Please enter your first name.\n");
	s_gets(pst->fname, NLEN);
	printf("Please enter your last name.\n");
	s_gets(pst->lname, NLEN);
}

void makeinfo(struct namect* pst)
{
	pst->letters = strlen(pst->fname) + strlen(pst->lname);
}

void showinfo(const struct namect* pst)
{
	printf("%s %s, your name contains %d letters.\n",
		pst->fname, pst->lname, pst->letters);
}

// 自己实现读取函数
char* s_gets(char* st, int n)
{
	char* ret_val;
	int i = 0;
	ret_val = fgets(st, n, stdin);
	if (ret_val) //即,ret_val != NULL
	{
		while (st[i] != '\n' && st[i] != '\0')
			i++;
		if (st[i] == '\n')
			st[i] = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}

运行测试
1111.png

示例2:返回结构体

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>

#define NLEN 30

struct namect {
	char fname[NLEN];
	char lname[NLEN];
	int letters;
};

char* s_gets(char* st, int n);
struct namect getinfo(void);
struct namect makeinfo(struct namect);
void showinfo(struct namect);

int main(int argc, char* argv[])
{
	struct namect person;

	person = getinfo();
	person = makeinfo(person);
	showinfo(person);

	system("pause");
	return 0;
}

struct namect getinfo(void)
{
	struct namect temp;
	printf("Please enter your first name.\n");
	s_gets(temp.fname, NLEN);
	printf("Please enter your last name.\n");
	s_gets(temp.lname, NLEN);
	return temp;
}

struct namect makeinfo(struct namect info)
{
	info.letters = strlen(info.fname) + strlen(info.lname);
	return info;
}

void showinfo(struct namect info)
{
	printf("%s %s, your name contains %d letters.\n",
		info.fname, info.lname, info.letters);
}

// 自己实现读取函数
char* s_gets(char* st, int n)
{
	char* ret_val;
	int i = 0;
	ret_val = fgets(st, n, stdin);
	if (ret_val) //即,ret_val != NULL
	{
		while (st[i] != '\n' && st[i] != '\0')
			i++;
		if (st[i] == '\n')
			st[i] = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}

运行测试
1111.png

传递结构体指针效率更高,若不希望被调函数修改结构体成员的值,可以在形参前加const限定符。

标签: C语言

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号