结构与指针

结构是由多个不同或者不同数据类型的成员组成的集合体。结构体以其封装特性应用较为广泛。提到结构体,不可避免会提到结构体指针。

#include "stdafx.h"
#include <iostream>

using namespace std;

typedef struct student
{
	char firstname[20];
	char* lastname;
	int score;
}student;

int _tmain(int argc, _TCHAR* argv[])
{
	student* stu;
	stu=(student*)malloc(sizeof(student));
	cin>>stu->firstname;
	stu->lastname=(char*)malloc(10*sizeof(char));
	cin>>stu->lastname;
	cin>>stu->score;
	
	cout<<"Firstname:"<<stu->firstname<<endl;
	cout<<"Lastname:"<<stu->lastname<<endl;
	cout<<"score:"<<stu->score<<endl;

	system("pause");
	return 0;
}
注意事项: 对于上述student结构体中成员firstname为数组名,指针常量,是不可以直接将字符串赋值给它;对于lastname指针变量,要想通过输入方式赋值,必须先对其分配内存。
看如下程序,主要加入了一个指针数组,数组元素为结构体变量。

#include "stdafx.h"
#include <iostream>

using namespace std;

typedef struct student
{
	char* name;
	int score;
	struct student* next;
}student;

int _tmain(int argc, _TCHAR* argv[])
{
	student st[]={{"John",90,st+1},{"Mary",85,st+2},{"Peter",92,st}};
	student *ptr[]={st,st+1,st+2};
	
	cout<<(*ptr)->name<<" "<<(**ptr).name<<endl;
	cout<<(*ptr)->score<<" "<<ptr[0]->score<<endl;
	cout<<(*ptr)->next->name<<endl;
	cout<<(*ptr)->next->next->name<<endl;
	
	cout<<(++(*ptr)->next)->name<<endl;

	cout<<(*ptr)->next->score<<endl;
	system("pause");
	return 0;
}

此种类似问题,只要把相应关系梳理好,结果是较为简单的,图如下:


结果为;


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值