当前位置:网站首页>C language elementary (VII) structure

C language elementary (VII) structure

2022-06-21 13:22:00 Princess Kaka

One . Structure operation

1. Address fetch

struct Point3D{
    int x;
    int y;
    int z;  
};

struct Point3D p = {1,2,3};
printf("&p = %p\n",&p);
printf("&(p.x) = %p\n",&p.x);
printf("&(p.y) = %p\n",&p.y);
printf("&(p.z) = %p\n",&p.z);

The structure name is not the address of the structure variable , must Use & Get address .
The array name is the address .

2. The ginseng

void Print(struct Point3D p){
    printf("(%d,%d,%d)",p.x,p.y,p.z);
}

  The entire structure is passed into the function as the value of the parameter . At this time Create a new structure variable in the function and copy the value . Structure can be used as a return value , It is also the overall copy of the structure .

Two . Structure pointer

struct Point3D p = {1,2,3};
struct Point3D* q = &p;

 1. Structure pointer Visiting members

Structure variables use . And name access members .
Structure pointers use -> And name access members . 

struct Point3D p = {1,2,3};
struct Point3D* q = &p;
printf("(%d,%d,%d)",q->x,q->y,q->z); //  Equate to printf("(%d,%d,%d)",(*q).x,(*q).y,(*q).z);

  By modifying the structure pointer q Members pointed to , It also changes the structure variable p Members of the value of the .

2. Structure pointer As a parameter  

void Print(struct Point3D* p){
    printf("(%d,%d,%d)",p->x,p->y,p->z);//  Equate to printf("(%d,%d,%d)",(*q).x,(*q).y,(*q).z);
}

  3、 ... and . Structure array

struct Point3D ps[] = {
   {1,2,3},{1,1,1},{0,0,0}};
for(int i=0;i<3;++i){
    printf("(%d,%d,%d)\n",ps[i].x,ps[i].y,ps[i].z);
}

Four . Nested structure

struct Line{
    struct Point3D start;
    struct Point3D end;
};
struct Line line = {
   {1,1,1},{0,0,0}};
//  Use 
printf("(%d,%d,%d)~(%d,%d,%d)",
line.start.x,line.start.y,line.start.z,
line.end.x,line.end.y,line.end.z);

struct Line* p = &line;
printf("(%d,%d,%d)~(%d,%d,%d)",
p->start.x,p->start.y,p->start.z,
p->end.x,p->end.y,p->end.z);

Structure contains an array of structures : 

struct Triangle{
    struct Point3D p[3];
};

struct Triangle t = {
   {
   {1,2,3},{1,1,1},{0,0,0}}};
原网站

版权声明
本文为[Princess Kaka]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211055027141.html