结构体指针
  C

结构体指针

 次点击
9 分钟阅读

结构体指针

作用:通过指针访问结构体的成员

语法:struct 结构体名 *指针名;

利用操作符->可以通过结构体指针访问结构体属性

#include <stdio.h>
#include <string.h>

//结构体的定义
struct book
{
	int num;
	char name[16];
	char author[16];
	char press[32];
	float price;
}book4,book5 = {3,"小王子","王五","邮电出版社",34},book6 = {.num = 3,.price = 78},book7[2];

int main(int argc, const char *argv[])
{
	/*指针访问普通变量
	 */
	struct book *p = &book4;
	struct book *q;
	q = &book5;

	p->num = 1;
	strcpy(p->name,"C和指针");
	strcpy(p->author,"张三");
	strcpy(p->press,"邮电出版社");
	p->price = 34;

	printf("num = %d, name = %s, author = %s, press = %s, price = %f\n", \
			p->num, p->name, p->author, p->press, p->price);
	printf("num = %d, name = %s, author = %s, press = %s, price = %f\n", \
			q->num, q->name, q->author, q->press, q->price);

	/*通过指针怎么访问数组
	 */
	struct book *pp = book7;
	pp->num = 2;
	strcpy(pp->name,"C和指针");
	strcpy(pp->author,"张三");
	strcpy(pp->press,"邮电出版社");
	pp->price = 45;
	printf("num = %d, name = %s, author = %s, press = %s, price = %f\n", \
			pp->num, pp->name, pp->author, pp->press, pp->price);
	
	//第一种方式,把指针当做数组的方式去访问
	pp[1].num = 5;
	strcpy(pp[1].name,"C和指针");
	strcpy(pp[1].author,"张三");
	strcpy(pp[1].press,"邮电出版社");
	pp[1].price = 45;
	printf("num = %d, name = %s, author = %s, press = %s, price = %f\n", \
			book7[1].num, book7[1].name, book7[1].author, book7[1].press, book7[1].price);
	
	//第二种方式,移动指针的位置来访问
	pp++;
	printf("num = %d, name = %s, author = %s, press = %s, price = %f\n", \
			pp->num, pp->name, pp->author, pp->press, pp->price);

	return 0;
}

结构体嵌套

含义:结构体中的成员可以是另一个结构体

语法:

 struct  结构体名 
 { 
 	struct 结构体名   成员名;	
 };
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct person
{
	char name[16];
	int age;
};

struct teacher
{
	int num;   //工号
	char work[16];
	struct person s;
};

struct student
{
	char num[16]; //学号
	float score;
	struct person s;
};
int main(int argc, const char *argv[])
{
	struct student stu;
	strcpy(stu.num,"20300978");
	stu.score = 98;
	strcpy(stu.s.name,"张三");
	stu.s.age = 18;

	printf("num = %s, name = %s, age = %d, score = %f\n",\
			stu.num, stu.s.name, stu.s.age, stu.score);

	struct teacher t;
	struct teacher *T = &t;
	T->num = 1001;
	strcpy(T->work,"处长");
	strcpy(T->s.name,"李四");
	T->s.age = 56;

	printf("num = %d, name = %s, age = %d, work = %s\n",\
			T->num, T->s.name, T->s.age, T->work);
	

	struct teacher *p = NULL;
	p = (struct teacher *)malloc(sizeof(struct teacher));
	if(p == NULL)
	{
		printf("malloc failed\n");
		return -1;
	}

	p->num = 1002;
	strcpy(p->work,"讲师");
	strcpy(p->s.name,"王五");
	p->s.age = 30;

	printf("num = %d, name = %s, age = %d, work = %s\n",\
			p->num, p->s.name, p->s.age, p->work);

	return 0;
}

© 本文著作权归作者所有,未经许可不得转载使用。