Pointer to struct variable

Source: Internet
Author: User

Definition:

The pointer to the struct variable is the starting address of the occupied memory segment. You can set a pointer variable to point to a struct variable. The value of this pointer variable is the starting address of the struct variable.

If p is an array pointing to the struct variable, you can call the member in the struct pointed to 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.

 

#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;}

The structure array is the same as other arrays. the array of one-dimensional arrays represents the address of the first element.

We know that struct can contain many types of member variables. Can it contain pointer variable members? The answer is yes.

Can it also contain struct variables pointing to similar structures? Of course, this principle is applied to linked lists.

 

# Include <iostream> # include <string> using namespace std; struct Candidate {string name; int count; Candidate * next; // defines the pointer to a variable of the Candidate type }; 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_leade R; while (p! = NULL) {cout <p-> name <":" <p-> count <endl; p = p-> next;} return 0 ;}

 

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.