• C/C++结构体


    结构变量的声明和初始化

    #include <cstdio>
    
    int main()
    {
        struct {
            int age;
            int height;
        } x, y = {29, 180};
        
        // 结构的成员在内存中按照声明的顺序存储 
        x.age = 30;
        x.height = 170;
        
        return 0;
    }

    结构类型——结构标记

    #include <cstdio>
    
    int main()
    {
        struct struct_name {
            int age;
            int height;
        } x; // 同时声明了【结构标记struct_name】和【结构变量x】 
        
        struct struct_name y; // 纯C时必须加上struct 
        
        struct_name z; // C++编译器则不必加struct  
        
        return 0;
    }

    结构类型——typedef

    #include <cstdio>
    
    int main()
    {
        typedef struct {
            int age;
            int height;
        } struct_name; 
        
        struct_name x;
        
        return 0;
    }

    C风格结构体

    传递指向结构的指针来代替传递结构可以避免生成副本。

    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    
    struct _Student {
        char* name;
        int age;
        int score;
    };
    typedef struct _Student* Student;
    
    Student newStudent(char* name, int age, int score)
    {
        Student result = (Student) malloc(sizeof(struct _Student));
        result->name = name;
        result->age = age;
        result->score = score;
        
        return result; 
    }
    
    void printStudent(Student x)
    {
        printf("%s %d %d
    ", x->name, x->age, x->score);
    }
    
    
    int main()
    {
        Student a, b;
        a = newStudent("asd", 19, 100);
        b = newStudent("dad", 12, 110);
        printStudent(a);
        printStudent(b);
        
        return 0;
    }
  • 相关阅读:
    BZOJ 1492 [NOI2007]货币兑换Cash
    BZOJ 2285 [Sdoi2011]保密
    BZOJ 2962 序列操作
    BZOJ 3197 [Sdoi2013]assassin
    BZOJ 3131 [Sdoi2013]淘金
    BZOJ 3532 [Sdoi2014]Lis
    BZOJ 1923 [Sdoi2010]外星千足虫
    BZOJ 4855 [Jsoi2016]轻重路径
    BZOJ 4289 PA2012 Tax
    微信开发之 微信支付
  • 原文地址:https://www.cnblogs.com/xkxf/p/14436801.html
Copyright © 2020-2023  润新知