指向结构的指针

作者:追风剑情 发布于:2020-1-19 16:01 分类:C

示例

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

#define LEN 20

const char* msgs[] =
{
	"   Thank you for the wonderful evening, ",
	"You certainly prove that a ",
	"is a special kind of guy. We must get together",
	"over a delicious ",
	" and have a few laughs"
};

struct names {
	char first[LEN];
	char last[LEN];
};

struct guy {
	struct names handle; //嵌套结构
	char favfood[LEN];
	char job[LEN];
	float income;
};

/*
在有些系统中,一个结构的大小可能大于它各成员大小之和。
这是因为系统对数据进行校准的过程中产生了一些“缝隙”。
例如,有些系统必须把每个成员都放在偶数地址上,或4的位数
地址上。在这种系统中,结构的内部就存在未使用的“缝隙”。
*/

int main(int argc, char* argv[])
{
	// 初始化一个结构变量
	struct guy fellow[2] = {
		{	{ "Ewen", "Villard" },
			"grilled salmon",
			"personality coach",
			68112.00
		},
		{
			{ "Rodney", "Swillbelly" },
			"tripe",
			"tabloid editor",
			432400.00
		}
	};
	struct guy* him; /* 这是一个指向结构的指针 */
	
	printf("address #1: %p #2: %p\n", &fellow[0], &fellow[1]);
	/* 和数组不同,结构名并不是结构的地址。 him=fellow[0](错误) */
	him = &fellow[0]; /* 告诉编译器该指针指向何处 */
	printf("pointer #1: %p #2: %p\n", him, him + 1);
	/* 
	.运算符比*运算符优先级高,
		
	&与*是一对互逆运算
	 him==&fellow[0]
	*him==fellow[0]
	假设 him == &barney
	下面的关系恒成立:
	barnet.income == (*him).income == him->income
	*/
	printf("him->income is $%.2f: (*him).income is $%.2f\n",
		him->income, (*him).income);
	him++; /* 指向下一个结构 */
	printf("him->favfood is %s: him->handle.last is %s\n",
		him->favfood, him->handle.last);

	system("pause");
	return 0;
}

运行测试

111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号