结构与指针
来源:互联网 发布:淘宝店怎么经营 编辑:程序博客网 时间: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
- 结构体与指针
- 结构 与 指针
- 指针与结构
- 结构体与指针
- 结构与指针
- 指针与结构体
- 结构体与指针
- 指针与结构体
- 结构体与指针
- 结构体与指针
- 指针与结构体、函数指针
- C语言指针-----指针与结构体
- 链表--结构与指针使用
- 结构体变量与指针
- 五.指针与结构
- 初识结构体与指针
- (五十八)结构与指针
- 结构体数组与指针
- Skia简介以及在Windows下编译操作步骤
- 初学者享受在魔兽世界与成功策略
- 全文本SDK与数据捕捉SDK比较
- 冲突战队作弊工具的Android IOS
- 冲突家族秘籍的Android没有调查没有密码
- 结构与指针
- 在xcode5中修改整个项目名
- Cocos2d-x 地图行走的实现1:图论与Dijkstra算法
- Android中通过xml资源文件定义数组
- 船务代理,货运从中国到加拿大的优势
- 程序员编程艺术:第二章、字符串是否包含问题
- 筹办婚礼在大雨中,恶劣的高温或低温将是一个最糟糕的决定
- java生成excel文件工具类实例
- 床垫厂要保持创新对于全新能力。首先床垫制造厂Opinio