蓝鸥iOS从零基础到精通就业-C语言入门 14结构体二

本文通过实例详细介绍了C语言中的结构体使用方法,包括结构体的定义、内存分配方式及结构体数组的排序等。此外,还展示了如何利用结构体来组织复杂的数据类型。

蓝鸥iOS从零基础到精通就业-C语言入门

 (学习路径http://blog.csdn.NET/lanouluanbin/article/details/53518018)

14结构体二

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
   
    struct dog {
        int age;
        char type[50];
        char name[30];
        float price;
        
    };
    typedef struct dog Dog;
    
    //创建四只小狗
    Dog dog1 = {4,"哈士奇","逗比哈",1000.0};
    Dog dog2 = {6,"金毛","暖暖",1100.0};
    Dog dog3 = {2,"阿拉斯加","水哥",1500.0};
    Dog dog4 = {3,"泰迪","小黄",600.0};
    
    //结构体数组
    Dog dogs[4] = {dog1,dog2,dog3,dog4};
    //打印阿拉斯加的价钱
    float price = dogs[2].price;
    printf("阿拉斯加的价格为%.2f\n",price);
    //修改泰迪的价格
    dogs[3].price = 900.0;
    //打印数组中四只小狗的所有信息
    for (int i = 0; i<4; i++) {
        printf("小狗的信息是:%d %s %s %.2f\n",dogs[i].age,dogs[i].type,dogs[i].name,dogs[i].price);
    }
    
    //对数组中的四只小狗按照价钱升序排列
    for (int i = 0; i<4-1; i++) {
        for (int j = 0; j<4-i-1; j++) {
            if (dogs[j].price > dogs[j+1].price) {
                
                Dog tempDog = dogs[j];
                dogs[j] = dogs[j+1];
                dogs[j+1] = tempDog;
                
            }
        }
    }
    //遍历查看排序的结果
    for (int i = 0; i<4; i++) {
        printf("===小狗的信息是:%d %s %s %.2f\n",dogs[i].age,dogs[i].type,dogs[i].name,dogs[i].price);
    }
    
    //1结构体内存分配
    struct stu {
        char a;//1
        int b;//4
        char c;//1
        long d;//8
        char e[20];//20
        float f;//4
    };
    struct stu s1 = {0};
    printf("所占字节数为%ld\n",sizeof(s1));
    //2结构体的嵌套

    
    
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值