结构与指针

来源:互联网 发布:淘宝店怎么经营 编辑:程序博客网 时间:2024/06/01 08:21

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

#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
原创粉丝点击