C语言 结构体指针类型的全局变量使用

定义结构体

文件1 <GlobalVar1.h>

/*******************************
*	file:	GlobalVar1.h
*	author:	hehl
*	time:	2019/11/5
*******************************/
#ifndef __GLOBALVAR1_H__
#define __GLOBALVAR1_H__

#include <stdlib.h>
typedef struct s1
{
	int x;
	int y;
}S;

#endif

定义结构体指针全局变量

文件2 <GlobalVar1.c>

/*******************************
*	file:	GlobalVar1.c
*	author:	hehl
*	time:	2019/11/5
*******************************/
#include "GlobalVar1.h"
S* g_struct = NULL;		// 定义

全局变量的引用、初始化、赋值

文件3<GlobalVar.c>

/*******************************
*	file:	GlobalVar.c
*	author:	hehl
*	time:	2019/11/5
*******************************/
#include <stdio.h>
#include <stdlib.h>
#include "GlobalVar1.h"
int main()
{
	extern S* g_struct;	 				// 引用结构体指针全局变量
	S* ss = (S*)calloc(1, sizeof(S));	// 初始化,分配内存空间
	g_struct = ss;						// 赋值

	g_struct->x = 3;
	g_struct->y = 5;

	printf("x is %d\n", g_struct->x);
	printf("y is %d\n", g_struct->y);

	free(g_struct);

	return 0;
}
}

编译、运行(Cygwin–在Windows系统下的模拟的Linux一款软件)

在这里插入图片描述

发布了9 篇原创文章 · 获赞 2 · 访问量 8565

猜你喜欢

转载自blog.csdn.net/hhl_work/article/details/102912129
今日推荐