zoukankan      html  css  js  c++  java
  • C语言基础:C语言结构体(3)

    前面我们讲解了结构体在内存中是如何存储的, 这次我们来讲解一下结构体定义的一些基本认识.


    下面我们看一个例子:

    #include <stdio.h>
    
    int main()
    {
        struct Student stu
        {
            int age;    //年龄
            double height;  //身高
            char *name; //名称
        };
        
        return 0;
    }

    上面这是我们之前学习的结构体定义方式, 其实还有几种方式, 让我们来继续往下看:

    1. 定义类型的同时定义变量

        struct Student
        {
            int age;
            double height;
            char *name;
        }stu;
    

    2. 定义类型后再定义变量

        struct Student
        {
            int age;
            double height;
            char *name;
        };
        struct Student stu;

     3.  定义类型的同时定义变量(省略了类型名称)

        struct
        {
            int age;
            double height;
            char *name;
        }stu;
        struct stu;


    还有一个关于结构体的作用域:

     1> 定义在函数外面:全局有效(从定义类型的那行开始,一直到文件结尾)

     2> 定义在函数(代码块)内部:局部有效(从定义类型的那行开始,一直到代码块结束)


    注意事项:

    结构体和其他变量一样, 不能重复定义同类型名的结构体比如:

         struct Student
         {
            int age;
            double height;
            char *name;
         } stu;
         
         struct Student
         {
            int age;
            double height;
            char *name;
         } stu2;

    上面这这种写法编译器是会报错的, 如果需要一个结构体多用, 那就需要像下面这样子:

         struct Student
         {
         int age;
         double height;
         char *name;
         } stu;
         
         struct Student stu2;

    这样子就可以实现一个结构体多个变量名重用, 而它们相互之间不会相互影响~~~



    好了这次就讲到这里, 下次我们继续~~~


  • 相关阅读:
    ERROR 1045 (28000): Access denied for user root@localhost (using password:
    MySQL: InnoDB 还是 MyISAM?
    PHP系统函数
    为什么分离数据库软件和数据库服务?
    C#索引器的作用及使用
    asp.net 中Session的运用,及抛出错误“未将对象引用设置到对象的实例”
    C#父类对象和子类对象之间的转化
    C#中属性简写原理
    c# 中Intern的作用
    C# 中ref和out的区别
  • 原文地址:https://www.cnblogs.com/iOSCain/p/4282884.html
Copyright © 2011-2022 走看看