C语言----结构体

来源:互联网 发布:mac 文件共享 编辑:程序博客网 时间:2024/06/05 13:26

一、结构体赋值

数组本身是不能直接相互赋值的;
可以通过把 数组 放在 结构体里 ,用结构体去赋值,因为结构体是可以相互赋值的。

二、 结构体内存对齐

1、以最⼤大成员变量类型所占空间的最小整数倍为分配单位;
2、按结构体成员声明顺序自上而下分配;
3、尽可能的减少碎片空间。

注:分配空间不足以存储成员变量时,分配新的空间单位。

三、例代码

////  main.m//  C_Project_07////  Created by on 15/3/19.//  Copyright (c) 2015年 . All rights reserved.//#import <Foundation/Foundation.h>/*struct student{    int number;    char name[20];    char gender;    float score;};//可以通过 typedef 语法将原有类型定义成新的类型,方便代码书写,以及提高代码的阅读性//typedef 的作用相当于给原有类型 struct student 起了别名(绰号)Student ,在定义之后使用即可以使用原有写法,也可以使用别名typedef struct student Student;*/typedef struct student{    int number;    char name[20];    int age;    float score;}Student;//类型定义 typedef 通常是在构造结构体 类型时以如下连用方式定义新的类型名,简化代码,方便后期使用该结构体类型typedef struct NBPoint{    float x;    float y;}NBPoint;typedef struct NBRectangle{    NBPoint origin;    float width;    float height;}NBRect;int main(int argc, const char * argv[]){//    struct student stu1 = { 1001, "Duke", 'm', 99 };//   //    Student stu2 = { 1002, "Leo", 'm', 70 };//   ////  结构体类型属于构造类型,所以其定义的变量不能直接参与运算,可以使用变量名加成员名的形式单个访问//   //    stu2.score = 120;//    printf( "学号:%d, 姓名:%c, 性别:%c, 成绩:%0.2f \n", stu2.number, stu2.name[0], stu2.gender, stu2.score );//   //    //与数组不同的是,相同类型的结构体,可以相互赋值;//    // 可以通过把 数组 放在结构体内实现数组的直接赋值//   //    Student stu3 = stu1;//    printf( "%s\n", stu3.name );//       // 有三个学生,编程找出分数最高的以及年龄最小的//   //    Student stu[3] = {0}, temp1, temp2;//   //    for ( int i = 0; i < 3; i++ )//    {//        printf( "请输入一个学生的学号,姓名,年龄,成绩:\n" );//        scanf( "%d %s %d %f" , &stu[i].number, stu[i].name, &stu[i].age, &stu[i].score );//    }//   //    for ( int i = 0; i < 3 - 1 ; i++ )//    {//        temp2 = stu[i].age > stu[i + 1].age ? stu[i + 1] : stu[i];//        temp1 = stu[i].score < stu[i + 1].score ? stu[i + 1] : stu[i];//    }//   //    printf( " \n成绩最高的学生的信息:\n学号:%d\t姓名:%s\t年龄:%d\t成绩:%0.2f\n\n年龄最小的学生的信息:\n学号:%d\t姓名:%s\t年龄:%d\t成绩:%0.2f\n",//           temp1.number, temp1.name, temp1.age, temp1.score, temp2.number, temp2.name, temp2.age, temp2.score );//    NBRect rect = { { 100, 100 }, 30, 100 };//   //    rect.origin.x = 200;//       Student stu[5] = {0}, temp;    for ( int i = 0; i < 5; i++ )    {        printf( "请输入一个学生的学号,姓名,年龄,成绩:\n" );        scanf( "%d %s %d %f" , &stu[i].number, stu[i].name, &stu[i].age, &stu[i].score );    }    for ( int i = 0; i < 5 - 1 ; i++ )    {        for ( int j = 0; j < 5 - i - 1; j++ )        {            if ( stu[j].score < stu[j + 1].score )            {                temp = stu[j + 1];                stu[j + 1] = stu[j];                stu[j] = temp;            }        }    }    printf( "\n按成绩从高到底排序后的学生的信息:\n" );    printf( " \n学号:\t姓名:\t年龄:\t成绩:\n" );    for( int i = 0; i < 5; i++ )        printf( " \n%d\t%s\t%d\t%0.2f\n",           stu[i].number, stu[i].name, stu[i].age, stu[i].score );    return 0;}
0 0
原创粉丝点击