C中的结构体

2019-08-28  本文已影响0人  一__谷__作气

C语言的结构体生成以及赋值方法,打点调用,以及->调用

#include "stdafx.h"

//第一种方式
struct Student
{
       int age;
       float score;
       char name[100];
       char sex;
};

//第二种方式,最常用
struct Student2
{
       int age;
       float score;
       char name[100];
       char sex;
} st2;

//第三种方式
struct
{
       int age;
       float score;
       char sex;
} st3;

int main()
{      
       //初始化赋值 定义的同时赋初值
       struct Student st = { 18,100,"gfg",'M' };
       struct Student st2;
       st2.age = 16;
       st2.sex = 'F';
       st2.score = 99;


       //第二种赋值
       struct Student *st4 = &st;
       st4->age = 20;
       //st4->age 在内部会转化为(*st4).age

       st4->sex = 'F';
       st4->score = 80;
    return 0;
}

赋值总结:
如何取出以及赋值结构体中的成员变量
1.结构体变量.成员名
2.指针变量->成员名
因为st4->age 在内部会转化为(*st4).age
这两种方式是等价的
st2->age的含义:st2所指向的那个结构体变量中的age这个成员

结构体的输入输出


#include "stdafx.h"
#include <string.h>
struct Student
{
       int age;
       char sex;
       char name[100];
};
void inputStudent(struct Student * st);//输入函数传发送的是地址
//void outputStudent(struct Student ss);//输出函数传参发送的是内容
/*
    优缺点:
            1.如果发送内容,在该程序内就会占用108个字节,速度慢,占内存
            2.如果发送地址,就会只占用一个指针的大小 速度快

            3.输出函数,不对结构体做任何操作,但是传指针,就会导致该输出函数不安全
            (可以用const解决)
            为了节省内存以及提高执行的速度,推荐传参发送地址即输入函数的方式
*/
void outputStudent(const struct Student *ss);




int main()
{

       struct Student st;
       inputStudent(&st);
       outputStudent(st);
       getchar();
    return 0;
}

void inputStudent(struct Student * st) {
       st->age = 18;
       strcpy(st->name, "张三");
       st->sex = 'F';
}
void outputStudent(const struct Student *ss) {
       printf("---age:%d\n---sex:%c\n---name%s",ss.age,ss.sex,ss.name);
}

上一篇下一篇

猜你喜欢

热点阅读