18天:指向结构的指针

117 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天,点击查看活动详情

1. 指向结构的指针

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

struct date *p = &myday;

(*p).month = 12;
p-> month=12;
  • 用->表示指针所指的结构变量中的成员
    • p-> month=12;
    • p所指的那个结构的month
output(*getStruct(&y));

print(getStruct(&y));

struct point *inputPoint(struct point *p)
{
    scanf ("%d", &p->x);
    scanf ("%d", &p->y);
    pintf("%d,%d\n",p->x,p->y)
    return p;
}
void output(struct point p)
{
    printf("%d,%d",p.x,p.y);
}
void print(struct point *p)
{
    printf("%d,%d",p->x,p->y);
}

分析:

  • 传进来一个指针,做完操作后再把这个指针返回出去了
  • 将来可以把这个函数串进其他函数的调用当中
  • print函数可以加const,因为输出不会被修改
  • output是输出结构本身
    • output(*getStruct(&y));
    • 取出这个函数的返回值作为这个函数的调用变量

2. 结构中的结构

  • 结构数组
  • struct date dates[100];
    • 一百个元素组成了一个数组
  • struct date dates[]={ {4,5,2005},{2,4,2005}};
  • 第一个大括号是dates0,第二个大括号是dates1
#include <stdio.h>

struct time {
	int hour;
	int minutes;
	int seconds;
};
struct time timeUpdate (struct time now);

int main (void) {
	struct time testTimes [5] = {
		{11, 59, 59}, {12, 0, 0}, {1, 29, 59}, {23, 59, 59}, {19, 12, 27}
	};
	int i;

	for (i = 0; i < 5; ++i) {
		printf("Time is %.2i:%.2i:%.2i",
		       testTimes[i].hour, testTimes[i].minutes, testTimes[i].seconds);
		testTimes[i] = timeUpdate(testTimes[i]);

		printf("...one second later it's %.2i:%.2i:%.2i\n",
		       testTimes[i].hour, testTimes[i].minutes, testTimes[i].seconds) ;
	}
	return 0;
}

struct time timeUpdate (struct time now) {
	++now.seconds;
	if ( now.seconds == 60) {
		now.seconds = 0;
		++now.minutes;
		if ( now.minutes == 60) {
			now.minutes = 0;
			++now.hour;
			if ( now.hour == 24) {
				now.hour = 0;
			}
		}
	}
}

分析:

  • 这个程序看起来很正常,但是调试结果不正常,返回的值错误,我也不知道错在哪里
  • 这个程序的逻辑是,把根据当前的时间,计算出下一秒的时间

结构中的结构

struct dateAndTime{
    struct date sdate;
    struct date stime;
}

嵌套的结构

struct point{
    int x;
    int y;
};
struct rectangle{
    struct point pt1;
    struct point pt2;
}
  • point表达一个点,rectangle表达一个矩阵。通过左上角和右下角这两个点就可以表达一个矩形。
  • 如果有变量,struct rectangle r;
  • 就可以有:r.pt1.x、r.pt1.y,r.pt2.x、和r.pt2.y
  • 点的左边是一个结构,r和r.pt1都是结构。
  • 如果有变量定义:
    • struct rectangle r,*rp;
    • rp=&r;
  • 那么下面的四种形式是等价的:
    • r.pt1.x
    • rp->pt1.x
    • (r.pt1).x
    • (rp->pt1).x
  • 但是没有rp->pt1->x(因为pt1不是指针)

总结

这节课学到了关于结构体指针的用法,以及调用结构体指针,指针的调用,结构体的嵌套。这节课学到了关于结构体指针的用法,以及调用结构体指针,指针的调用,结构体的嵌套。感觉这语言越学越难,尤其是上面那个程序,看起来跟老师的一模一样,结果就是有错误,在电脑上调试的时候是只能出8:00:00的时间,在线上编译器上,调试的结果是一堆乱码,太奇怪了,逻辑上没看出来有任何问题。