C + + pointers to struct-body variables

Source: Internet
Author: User

Transfer from http://www.jb51.net/article/42140.htm

Defined:

The pointer to the struct variable is the starting address of the memory segment that the variable is occupying. You can set a pointer variable to point to a struct variable, at which point the value of the pointer variable is the starting address of the struct variable.

Set P is an array that points to a struct variable, you can invoke the member in the struct that points to it in the following way:

(1) struct variable. Member name. For example, Stu.num.

(2) (*P). Member name. For example, (*p). Num.

(3) p-> member name. For example, P->num.

The code is as follows:

#include <iostream> #include <string>using namespace std;struct candidate{string name; int count;}; int main () {candidate c_leader[2]={"Tom", 5, "Marry", 8}; Candidate *p1,*p2; P1=c_leader; cout<< (*P1) .name<< ":" << (*P1) .count<<endl; p2=&c_leader[1]; cout<<p2->name<< ":" <<p2->count<<endl; return 0;}

  

Description, an array of one-dimensional arrays represents the address of the first element, as is the case with other arrays.

We learned that there are many types of member variables in a struct, so can we include pointer variable members? The answer is yes.

Is it possible to include struct variables that point to similar structures? Of course, the list is applied to this principle.

#include <iostream> #include <string>using namespace std;struct candidate{string name; int count; Candidate *next;//defines a pointer to a candidate type variable};int main () {    candidate c_leader[3]; c_leader[0].name= "Tom"; C_leader[0] . count=5; c_leader[0].next=&c_leader[1]; C_leader[1].name= "Nick"; c_leader[1].count=9; c_leader[1].next=&c_leader[2]; C_leader[2].name= "Jim"; c_leader[2].count=10; C_leader[2].next=null; Candidate *p=c_leader; while (p!=null) {  cout<<p->name<< ":" <<p->count<<endl;  can also (p+1)->name ... To implement  p=p->next;} return 0;}

  

C + + pointers to struct-body variables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.