007-结构体数组遍历

本文通过一个C语言示例介绍了如何定义结构体并使用三种不同方法遍历结构体数组,包括数组遍历、指针遍历及再次数组遍历的方式。
#include<stdlib.h>
#include<stdio.h>
#include<string.h>

// 结构体指针
struct Book{
    char *name;
    char *author;
    int page;
};

struct Computer {
    char *name;
    int price;
    double weight;
};

int main() {
    // 结构体数组
    struct Book books[2] ={
  
  {"西游记", "吴承恩", 100}, {"水浒传", "施耐庵", 200}};
    // 遍历结构体数组
    // 第一种遍历方式 数组遍历
    int i= 0;
    for (; i< 2; i++){
        printf("数组遍历1 book name is %s, author is %s, page is %d\n", books[i].name, books[i].author, books[i].page);
    }
    // 第二种遍历方式 指针遍历 在Windows上有问题
    i = 0;
    struct Book *pBooks = &books[0];
    // for (; pBooks < pBooks+1; pBooks++) {
    //     printf("指针遍历2  book name is %s, author is %s\n", pBooks->name, pBooks->author);
    // }
    for (; i <sizeof(books)/sizeof(struct Book); i++) {
        printf("指针遍历2 book name is %s, author is %s, page is %d\n", pBooks->name, pBooks->author, pBooks->page);
        pBooks++;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值