美文网首页
C中的结构体

C中的结构体

作者: 一__谷__作气 | 来源:发表于2019-08-28 15:39 被阅读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);
}

相关文章

  • C++系列 --- 结构体、权限修饰符、类简介

    一、结构体 结构体:自定义的数据类型 C++ 中的结构和C中的结构有什么区别? C++中的结构除具备了C中的所有功...

  • C++中结构体

    C++中结构体并不是C中的结构体了 C++的结构体更像是一种特殊的类 他与类一样 可以有public privat...

  • JNI总结

    java调用c/c++ 在C中:JNIEnv 结构体指针别名env二级指针 在C++中:JNIEnv 是一个结构体...

  • 深入理解Runtime中的isa

    objc_object Objective-C 所有对象都是 C 语言结构体objc_object,这个结构体中包...

  • 第九章 类和结构体

    c++中,结构体是稍有不同的类,类能做的,结构体也可以; 而swift中,结构体与类有较大区别, 结构体与类的区别...

  • C中的结构体

    C语言的结构体生成以及赋值方法,打点调用,以及->调用 赋值总结:如何取出以及赋值结构体中的成员变量1.结构体变量...

  • 【OC梳理】结构体、枚举

    结构体(struct) OC中的结构体(struct),其实就是C语言中的结构体(struct)常见使用方法。OC...

  • 面经---依依短租

    1. 结构体、共用体、类 C++中结构体与类的区别: 结构体中的成员访问权限不声明时候默认是 public 的,而...

  • C语言结构体

    结构体 本文介绍C语言结构体,struct 在C++中功能相对C较多,相当于类,这里暂时不讨论,本文单独讨论C语言...

  • C语言和OC的结构体(struct)

    Struct(结构体) 1.结构体定义 2.结构体变量 3.结构体数组 4.C语言结构体指针 5.C语言共用体 6...

网友评论

      本文标题:C中的结构体

      本文链接:https://www.haomeiwen.com/subject/gfqmectx.html