C语言笔记--结构体

结构体 struct

  • 结构体所占的空间,并不是简单的里面所包含的数据类型容量简单相加,因为存在对齐策略,会比预期要大
struct MyStruct  //结构体名
{

}; //注意一定要加;

这是基本格式,其余的见 笔记

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
struct student
{
    int num;
    char name[20];
    char sex;
    int age;
    float score;
    char daar[30];
}; //结构体类型声明,注意最后一定要加分号

int main(){
    
    struct student s={1001,"lele",'M',20,98.5,"Shenzhen"};//结构体变量
    //打印要一个一个来
    printf("%d %s %c %d %5.2f %s\n",s.num,s.name,s.sex,s.age,s.score,s.daar);

    system("pause");
    return 0;
}

结构体数组

struct student sarr[3];//结构体数组
    int i;
    //通过scanf for循环读取数据
    for (int i = 0; i < 3; i++)
    {
        //sarr[i].name  因为struct里面char name[20];是字符数组,所以开始是起始地址
        //不需要&sarr[i].name
        scanf("%d %s %c %d %f %s\n",&sarr[i].num,sarr[i].name,&sarr[i].sex,&sarr[i].age,&sarr[i].score,sarr[i].addr);

    }
    //打印输出来
        for (int i = 0; i < 3; i++)
    {
        
       printf("%d %s %c %d %f %s\n",sarr[i].num,sarr[i].name,sarr[i].sex,sarr[i].age,sarr[i].score,sarr[i].addr);

    }

 

结构体指针

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
struct student
{
 int num;
 char name[20];
 char sex;
};

int main(){
 
 struct student s={1001,"wangle",'M'};//结构体变量 也可以再结构体定义的最后写
 struct student* p;//结构体指针
 p=&s;
 printf("%d %s %c\n",(*p).num,(*p).name,(*p).sex); //()用括号的原因是.优先级最高,p是指针,不能.name 只能->name 这样会报错
 //也可与这样写
 printf("%d %s %c\n",p->num,p->name,p->sex);//->用于指针的成员选择
 
 struct student sarr[3]={1001,"lilei",'M',1005,"zhangsan",'M',1007,"lili",'F'};
 p=sarr;//p存的就是sarr数组起始地址
 
 int num=0;
 num=p->num++;
 printf("num=%d,p->num=%d\n",num,p->num);
 num=p++->num;
  printf("num=%d,p->num=%d\n",num,p->num);
 system("pause");
 return 0;
}

 

下面解释下:

 num=p->num++;
 printf("num=%d,p->num=%d\n",num,p->num);
 num=p++->num;
 printf("num=%d,p->num=%d\n",num,p->num);

num=p->num++;  跟i++很像

先num=p->num 结果为1001  ,然后 p->num++   p这时候为1002 

num=p++->num; 

->优先级跟.一样比 ++高 

所以num=p->num  这时候p的地址上存的num 是上面的1002

再p++ 地址++ 变为下一个地址 指向1005

 

结构体typedef

typedef的作用就是起别名

定义方式:

typedf  struct student {
   int num ;
   char name[20] ;
   char sex ;
}  stu , * pstu ;
  • stu 代表 struct student (给结构体类型起别名)

  • * pstu 代表 struct studen * (给结构体指针变量起别名)

  • typedef int INTEGER 起别名的作用在于代码即注释,比如size_t 这样可以快速知道作用

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>

//给结构体类型起别名,叫stu,起了结构体指针类型的别名,叫pstu
typedef struct student
{
    int num;
    char name[20];
    char sex;
}stu,*pstu;

//typedef _W64 unsigned int   size_t;  //size_t的定义
typedef int INEGER; //与size_t相似,起了个新类型INEGER int 型号

int main(){
    stu s={1001,"wangle",'M'};
    pstu p;//stu* p 就相当于一个结构体指针
    INEGER i= 10; //等价与int i=10;
    p=&s;//p指向s的地址
    printf("i=%d,p->num=%d\n",i,p->num);

    system("pause");
    return 0;
}

可以起别名,也可以直接当结构体使用

 

posted @ 2022-01-18 16:20  halfup  阅读(96)  评论(0编辑  收藏  举报