十三、结构类型(2)——结构

声明结构的形式

struct point{
    int x;
    int y;
};
struct point p1,p2;//p1,p2都是point,里面有x和y的值。 
struct point{
    int x;
    int y;
}p1,p2; //p1,p2都是point,里面有x和y的值。 
struct {
    int x;
    int y;
}p1,p2; //p1,p2都是一种无名结构,里面有x和y。 

对于第一种和第二种形式,都声明了结构point。但是第三种形式没有声明point,只是定义了两个变量。

结构变量

struct date today;
today.month=06;
today.day=19;
today.year=2005;

 结构初始化

#include<stdio.h>

struct date{
    int month;
    int day;
    int year;
};

int main()
{
    struct date today={07,31,2014
    };
    struct date thismonth={.month=7,.year=2014
    };
    
    printf("Today’s date is: %i-%i-%i.\n",today.year,today.month,today.day);
    printf("This month is: %i-%i-%i.\n",thismonth.year,thismonth.month,thismonth.day);
    
    
    return 0;
 }  
 
 

结构成员

 (1)结构和数组有点像。

(2)数组用[]运算符和下标访问其成员。

a[0]=10;

(3)结构用.运算符和名字访问其成员。

today.day
student.firstName
p1.x   
p1.y   
//当p1表示的是结构体名时,x,y表示变量名

结构运算

 (1)要访问整个结构,直接用结构变量的名字。

(2)对于整个结构,可以做赋值、取地址,也可以传递给函数参数

p1=(struct point){5,10};  //相当于p1.x=5;p2.y=10;
p1=p2; //相当于p1.x=p2.x;p1.y=p2.y;

数组无法做这两种运算

 复合字面量

today=(struct date){9,25,2004};

today=(struct date){.month=9,.day=25,.year=2004};

结构指针

 和数组不同,结构变量的名字并不是结构变量的地址,必须使用&运算符

struct date  *pDate=&today;

猜你喜欢

转载自www.cnblogs.com/Strugglinggirl/p/9079385.html