学结构体了

指针学完了,来学学结构体吧,走进了一个新的世界。

结构体:不同的数据类型组成的一个结构

一般形式:struct 结构体名

                    {成员表列};

声明:类型名 成员名

定义的方法:

先声明结构体类型,再定义该类型的变量

 

struct student
{
     int age;
     char name[20];
};//不要忘了末尾的';',结构体的声明

struct student student1;//定义


在声明的时候同时定义变量

 

 

struct student
{
    int age;
    char name[20];
}student1;

 

 

不指定类型名直接定义结构体变量(没有结构体名,不能再去定义其他结构体变量)

 

strcut 
{
    int age;
   char name[20];
}zhangsan;

 

 

 

要点:结构体变量的赋值和引用(结构体名,变量名)

 

结构体数组:数组的每个元素由结构体组成

看代码:定义个结构体数组然后打印

 

#inlcude<stdio.h>

struct people
{
    int age;
    char name[20];
}student[2]={18,"zhangdan",19,"lisi"};//定义结构体输组,声明定义一起完成

int main()
{
    for(int i=0;i<2;i++)
    {
       printf("%d,%s",student[i].age,student[i].name);
    }
    return 0;
}

打印:18,zhandgan

 

            19,lisi

 

声明和定义分开时:

 

struct people
{
     int age;
     char name[20];
};

struct people student[2]={18,"",19,"lisi"};


结构体指针:指针向结构体类型的指针变量(要注意其类型)

 

看代码:

 

#include<stdio.h>

struct people
{
    int age;
    char name[20];
};

int main()
{
     struct people people1={18,"lisi"};//定义结构体变量
     struct people *p=&people;//定义结构体指针,并赋予people1的地址,注意指针类型为结构体类型
      printf("%d,%s\n",people1.age,people1.name);//结构体变量名引用
      printf("%d,%s\n",p->age,p->name);//指针引用
      return 0;
}

 

 

结构体变量和结构体指针作为函数的参数:

 

#include<stdio.h>

struct people
{
     int age;
    char name[20];
};

struct student
{
     int age;
     char name[20];
}gs[2]={15,"zhandgan",16,"lisi"};

int print1(strcut people peopleN)//传入结构体变量
{
     printf("%d,%s\n",peopleN.age,people.name);
     return 0;
}

int print2(struct student[])//传入结构体数组
{
      for(int i=0;i<2;i++)
     {
          printf("%d,%s\n",gs[i].age,gs[i].name);
          return 0;
     }
}

int print3(struct people *p1)//传入结构体指针
{
     printf("%d,%s\n",p1->age,p1->name);
     return 0;
}

int main()
{
    struct people people1={18,"lisi"};
   strcut people *p=&people1;//定义结构体指针并赋值
   print1(people);
   print2(gs);
   print3(p);
    return 0;
}

全部打印出对应的值。

 

 

好了,结构体到这里就告一段落了,以后再学。


 

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值