struct 做另一个struct的成员

1. struct A 变量可以做另一个struct AB  的成员

2. struct A 的指针可以指向 struct AB 的变量

3. struct AB 的指针 也可以指向 struct A的变量,but dangerous

4. 一切都在内存空间,只是指针指向而已。


/*
 * test.h
 *
 *  Created on: Sep 27, 2012
 *      Author: caoj7
 */

#ifndef TEST_H_
#define TEST_H_

struct date{
	int year;
	int month;
	int day;
};

typedef struct date date_t;

struct timer{
	date_t date_member;
	int hour;
	int minute;
	int second;
};

typedef struct timer timer_t;


#endif /* TEST_H_ */

/*
 * test.c
 *
 *  Created on: Sep 27, 2012
 *      Author: caoj7
 */
#include <stdio.h>
#include <stdlib.h>
#include "test.h"

date_t birth_date = {2012, 9, 26};

int main(void){

	timer_t birth_timer = {birth_date, 1,1,1};
	timer_t *birth_timer_ptr = &birth_timer;
	printf("birth_timer is: %d %d %d, %d:%d:%d\n",
			birth_timer_ptr->date_member.year,
			birth_timer_ptr->date_member.month,
			birth_timer_ptr->date_member.day,
			birth_timer_ptr->hour,
			birth_timer_ptr->minute,
			birth_timer_ptr->second
			);

	birth_timer_ptr->date_member.year =  2000;
	printf("not change value in orginal struct, birth_date.year = %d\n", birth_date.year);
	printf("birth_timer is: %d %d %d, %d:%d:%d\n",
				birth_timer_ptr->date_member.year,
				birth_timer_ptr->date_member.month,
				birth_timer_ptr->date_member.day,
				birth_timer_ptr->hour,
				birth_timer_ptr->minute,
				birth_timer_ptr->second
				);
	//let a member pointer point to a whole struct address
	date_t *date_ptr = (date_t *)birth_timer_ptr;
	printf("%d %d %d\n", date_ptr->year, date_ptr->month, date_ptr->day);

	//
	timer_t *test_timer_ptr = (timer_t *)date_ptr;
	printf("%d %d %d, %d:%d:%d\n",
			test_timer_ptr->date_member.year,
			test_timer_ptr->date_member.month,
			test_timer_ptr->date_member.day,
			test_timer_ptr->hour,
			test_timer_ptr->minute,
			test_timer_ptr->second);

	test_timer_ptr = (timer_t *)&birth_date;
	printf("%d %d %d, %d:%d:%d\n",
				test_timer_ptr->date_member.year,
				test_timer_ptr->date_member.month,
				test_timer_ptr->date_member.day,
				test_timer_ptr->hour,
				test_timer_ptr->minute,
				test_timer_ptr->second);

	return EXIT_SUCCESS;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值