以下记载了在初学结构体时犯下的一些错误。
先来一些杂识
struct f { string name; }; struct students { int num; string name; students *next; students friends; // f fri; }; void main() { students boy[40]; students polyy,*li = &polyy; polyy.num; polyy.name; polyy.friends.name; polyy.next->num; li->num; li->name; li->friends.name; li->next->num; }
错误一:结构体内用本身定义实体
1 struct student 2 { 3 int num; 4 string name; 5 student friends; 6 };
因为在结构体执行完之前,是没有内存地址空间的。而第五行中定义了一个实体,显然是错的,应该用指针的形式
1 struct students 2 { 3 int num; 4 string name; 5 students *friends; 6 };
错误二:结构体声明中的错误
//正确的表示,结构体在用之前定义 struct student { int num; }; int main() { struct student poly; return 0; }
//错误 struct student; int main() { struct student poly; //wrong return 0; } struct student { int num; };
错误在于,还没运行结构体生成实体,就定义实体,没有空间(表达的不好。。。请大大们指正),要在第5行中定义成指针的形式就对了。与函数不同,函数只是调用,没有“额外的”地址空间产生。
//正确的 struct student; int main() { struct student* poly; return 0; } struct student { int num; };
链表学习
链表的基本操作主要就是创建链表、插入节点、删除节点和访问节点等。其形态为下:
struct linkRec { int data; linkRec *next; };
头结点:链表中的特殊节点,不存放数据,只是为保证每个元素都有一个前驱。多用于单链表中,特别是单链表在第一个节点前插入节点时。
链表的节点插入: 。
链表的节点删除与插入相反 p->next = p->next->next 即可,但要注意回收空间,防止内存泄露
//单链表的建立与访问 struct linkRec { int data; linkRec *next; }; int main() { int x; linkRec *head,*p,*rear; head = rear = new linkRec; while (true) { cin>>x; if (x == 0) break; p = new linkRec; p->data = x; //p = rear->next;//错误 rear->next = p;//将p链到表尾 rear = p; } rear->next = NULL; cout<<"Connects of the linkrec is : \n"; p = head->next; while (p != NULL) { cout<<p->data<<"\t"; p = p->next; } return 0; }
//约瑟夫环问题 struct node { int data; node *next; }; int main() { int n; node *p,*q,*head; p = head = new node; cout<<"Please input n : \t"; cin>>n; p->data = 0; for (int i = 1;i<n;i++) { q = new node; q->data = i; p->next = q; p = q; } p->next = head; q = head; while (q->next != q) { p = q->next;q = p->next; p->next = q->next; delete q; q = p->next; } cout<<q->data<<endl; return 0; }
struct studant1 { string sex; }; struct studant { int num; string name; studant1 se; }; int main() { studant poly,*p = &poly; cout<<"poly`s num name sex: \n"; cin>>p->num>>p->name; cout<<poly.num<<"\t"<<poly.name<<endl; cin>>p->se.sex; cout<<poly.se.sex<<endl;//p->se->sex<<endl; return 0; }
struct pointT { double x,y; }; pointT setpoint(double x,double y); pointT getpoint(double); int main() { pointT p1; p1 = setpoint(1,2); cout<<p1.x<<"\t"<<p1.y<<endl; return 0; } pointT setpoint(double x,double y) { pointT p; p.x = x; p.y = y; return p; }
各种表达错误,大大们指正啊
原文:http://www.cnblogs.com/kbe317/p/3832628.html