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一款軟件)

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章