结构体

Posted spore

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了结构体相关的知识,希望对你有一定的参考价值。

结构体

  为什么会出现结构体

    为了表示一些复杂的数据,而普通的基本类型的变量无法满足要求

  什么叫结构体

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

#include <stdio.h>
#include <string.h>

struct Student

    int sid;
    char name[200];
    int age;
; //分号不能省

int main()

    struct Student st = 1000, "zhangyan", 20;
    printf("%d %s %d\n",st.sid, st.name, st.age);
    
    st.sid = 99;
    //st.name = "lisi";  //error
    strcpy(st.name, "lisi");
    st.age = 20;
    printf("%d %s %d\n",st.sid,st.name, st.age);
    return 0;

 

  如何使用结构体

    两种方式:

      struct Student st = 1000, "zhangyan", 20;

      struct Student * pst = &st; 

        1. st.sid

        2. pst -> sid  pst所指向的结构体变量中的的sid这个成员(通常使用第二个)

   注意事项:

    结构体变量不能加减乘除,但可以相互赋值

    普通结构体变量和结构体指针变量作为函数传参的问题  

#include <stdio.h>
#include <string.h>

struct Student

    int sid;
    char name[200];
    int age;
; //分号不能省

void f(struct Student * pst);
void g(struct Student st);
void g2(struct Student * );
int main()

    struct Student st; //已经为st分配好地址
    f(&st);
    g2(&st);
    //printf("%d %s %d\n", st.sid, st.name, st.age);
    return 0;

//这种方式耗内存,耗时间,不推荐
void g(struct Student st)

   printf("%d %s %d\n", st.sid, st.name, st.age);


void g2(struct Student *pst)

    printf("%d %s %d\n", pst->sid, pst->name, pst->age);

void f(struct Student * pst)

    (*pst).sid = 99;
    strcpy(pst->name, "zhangsan");
    pst->age = 22;

 

    

 

以上是关于结构体的主要内容,如果未能解决你的问题,请参考以下文章

C语言-结构体

C 语言结构体 ( 结构体类型定义 | 结构体类型别名 | 声明结构体变量的三种方法 | 栈内存中声明结构体变量 | 定义隐式结构体时声明变量 | 定义普通结构体时声明变量 )

结构体定义是啥?

结构体指针

C++结构体中定义函数(C++结构体与C语言结构体区别)(C++结构体与C++类的区别)(结构体函数)

C++结构体中定义函数(C++结构体与C语言结构体区别)(C++结构体与C++类的区别)(结构体函数)