数据结构入门(三)——预备知识(2)——结构体

前言

本系列文章是笔者学习数据结构的笔记,如有不妥之处欢迎指正



结构体的优势

  • 能够表示普通的基本类型变量无法满足要求的复杂数据

什么是结构体

  • 结构体是用户根据实际需要自己定义的符合数据类型

如何使用结构体

#include<stdio.h>
struct Student
{
    
    
    int id;			//用户自定义变量
    char name[20];  //用户自定义变量
    int age;		//用户自定义变量
};

int main()
{
    
    
    struct Student st;	   //定义结构体变量
                           //使用结构体的两种方式
    st.id = 01;            //st.id为调用结构体变量的成员(内容)

    struct Student *pst;
    pst = &st;
    pst->age = 20;                                       //pst->id 等价于(*pst).id 等价于st.id
    scanf("%s",&pst->name);                      //使用scanf()等函数赋值同理
    printf("%d %s %d\n",st.id,st.name,st.age);   //st.XX为调用结构变量的内容(成员)

    return 0;
}

输入

abc

输出结果为

1 abc 20

pst->id是pst所指向的结构体变量中的id这个成员

注意:
1.结构体变量能够相互赋值但是不能运算


结构体的函数间传递

#include<stdio.h>
struct Student
{
    
    
    int id;
    int age;
};

void f(struct Student *pst);

int main()
{
    
    
    struct Student st;

    f(&st);

    printf("%d %d",st.id, st.age);
    
    return 0;
}

void f(struct Student *pst)
{
    
    
    (*pst).age = 20;
    pst->id =01;
}

输出结果为

15 20


猜你喜欢

转载自blog.csdn.net/qq_40016124/article/details/113078303