栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

结构体——c语言

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

结构体——c语言

为什么要用结构体    

如果你想表达的数据比较复杂,它不是一个值 比如你想表达日期  就有年月日三个值,如果想用一个整体去表达这么多集合在一起的数据   那么就需要用到 结构体

一个结构就是一个复合的数据类型

#include 
int main(int argc,char const *argv[])
{
    struct date {
    int month;
     int day;
      int year;
};
struct date toaay;
today. month = 07;
today.day = 31;
today .year = 2014;

printf( "Today's date is %i-%i-%i.n",
today.year,today.month,today.day ) ;

return 0;
}

在函数内/外?

和本地变量—样,在函数内部声明的结构类型只能在函数内部使用
所以通常在函数外部声明结构类型,
这样就可以被多个函数所使用了


声明结构的形式

三种方法

struct point {
int x;
int y;};

struct point pl, p2;pl和p2都是point     里面有x和y的值
 

struct  {
int x;
int y;}     p1,p2  ;

p1 和p2都是一种无名结构,里面有x和y

struct point {
int x;
int y;} pl, p2;

pl和p2都是point     里面有x和y的值

结构体的初始化
#include 
struct date {
int month;
int day;
int year;
};
int main(int argc, char const *argv[])
{
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. ln",
thismonth.year,thismonth.month,thismonth.day ) ;
return 0;
}

结构成员

结构和数组有点像
数组用运算符和下标访问其成员a[0] =10;
结构用.运算符和名字访问其成员

today.day            访问 today结构中的  day

p1.x                      访问p1结构中的 x


结构运算

要访问整个结构,直接用结构变量的名字对于整个结构,可以做赋值、取地址,也可以传递给函数参数
pl = (struct point){5,I0};相当于pl.x= 5;    pl.y = l0;

pl =p2;    相当于pl.x = p2.x; pl.y = p2.y;
数组无法做这两种运算!

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/690266.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号