C语言基础

    返回首页    发表留言
本文作者:李德强
          第三节 结构体数组与指针
 
 

一、结构体数组

        在这一讲中,我们来一起学习结构体数组的相关内容。在之前的两个小节中我们知道,结构体变量可以与普通变量一样使用。那么就可以跟普通变量一样定义数组。例如,我们可以这样定义一个具有3个元素的结构体数组变量:

typedef struct point_s
{
	float x;
	float y;
} point_s;

point_s pArray[3];

        那么,对于每一个结构体元素变量,都相当于一个普通结构体变量,它们可以像使用单独结构体变量一样使用。例如,我们可以分别对这3个元素进行赋值操作:

point_s pArray[3];
pArray[0].x = 1;
pArray[0].y = 2;
pArray[1].x = 3;
pArray[1].y = 4;
pArray[2].x = 5;
pArray[2].y = 6;

        当然,对于数组变量来说,我们可以使用循环的方式来对结构体进行操作,例如,我们来求出数组中横坐标与纵坐标为平均值的点坐标:

#include <stdio.h>
#include <math.h>

typedef struct point_s
{
	float x;
	float y;
} point_s;

int main(int argc, char *argv[])
{
	point_s pArray[3];
	pArray[0].x = 1.6;
	pArray[0].y = 1.1;
	pArray[1].x = 3.8;
	pArray[1].y = 4.1;
	pArray[2].x = 2.5;
	pArray[2].y = 1.6;

	point_s p;
	p.x = 0;
	p.y = 0;
	for (int i = 0; i < 3; i++)
	{
		p.x += pArray[i].x;
		p.y += pArray[i].y;
	}
	p.x /= 3;
	p.y /= 3;

	printf("%4.2f %4.2f\n", p.x, p.y);
	return 0;
}

 

二、结构体与指针

        结构体指针变量的本质就是一个结构体类型的指针变量。也就是说,我们有一个指针用于指向某一个结构体变量,即:指针中存放的是结构体变量的地址。例如:

#include <stdio.h>
#include <math.h>

typedef struct point_s
{
	float x;
	float y;
} point_s;

int main(int argc, char *argv[])
{
	point_s point;
	point.x = 1.6;
	point.y = 1.1;
	point_s *p = &point;
	printf("%4.2f %4.2f\n", p->x, p->y);
	return 0;
}

1.60 1.10

        这样我们就定义了一个结构体指针变量,我们可以使用p->x来使用结构体变量内部的属性。对于结构体指针我们需要注意的是:当结构体指针做为函数参数时,在函数内部通过指针来修改结构体属性的值时,会修改其外部原变量 的值。例如:

 

#include <stdio.h>
#include <math.h>

typedef struct point_s
{
	float x;
	float y;
} point_s;

void func(point_s *p)
{
	p->x = 3.6;
	p->y = 4.2;
}

int main(int argc, char *argv[])
{
	point_s point;
	point.x = 1.6;
	point.y = 1.1;
	point_s *p = &point;
	func(p);
	printf("%4.2f %4.2f\n", p->x, p->y);
	return 0;
}

        也就是说,指针变量做参数时,实际上是将外部原变量的内存地址做为参数传入函数内部。而在函数内部通过这个指针修改其属性值则会直接改变外部原变量的属性值。这个特性与普通指针变量一致。

        接下来我们来一起看看结构体数组与指针的关系,例如,我们首先定义一个结构体数组,并定义一个指针变量指向这个数组元素的首地址:

#include <stdio.h>
#include <math.h>

typedef struct point_s
{
	float x;
	float y;
} point_s;

void func(point_s *p)
{
	p->x = 3.6;
	p->y = 4.2;
}

int main(int argc, char *argv[])
{
	point_s arr[3];
	arr[0].x = 1;
	arr[0].y = 1;
	arr[1].x = 2;
	arr[1].y = 2;
	arr[2].x = 3;
	arr[2].y = 3;

	point_s *p = &arr[0];
	printf("%4.2f %4.2f\n", p->x, p->y);

	p++;
	printf("%4.2f %4.2f\n", p->x, p->y);

	p++;
	printf("%4.2f %4.2f\n", p->x, p->y);

	return 0;
}

1.00 1.00
2.00 2.00
3.00 3.00

        值得注意的是:指针变量在做++或+--操作时,以及其它算数运行运算时,它的计算单位是勘察其指向变量类型的字节大小,而不是一1个字节。也就是说:point_s *p指针了一个point_s型结构体变量,这个结构体所占用的内存大小 是8个字节(1个float占用4个字节)那么当p++时,实际上是指向了下一个数组元素,而不是指向了下一下字节,我们来看一下内存内容:

 

 

    返回首页    返回顶部
  看不清?点击刷新

 

  Copyright © 2015-2023 问渠网 辽ICP备15013245号