C语言,结构体指针案例

案例一:

c 复制代码
#include <stdio.h>
#include <stdbool.h>
#include <string.h>  // 添加string.h头文件用于strcpy
//结构体指针

//方式 1 : 先定义结构体
struct Dog
{
    char *name;
    int age;
    char weight;
};

//方式 1 : 
char *get_dog_info(struct Dog dog)
{
    static char info[40];
    sprintf(info, "name:%s, age:%d, weight:%d", dog.name, dog.age, dog.weight);
    return info;
};

char *get_dog_info1(struct Dog *dog)
{
    static char info1[30];//静态局部指针变量
    sprintf(info1, "name:%s, age:%d, weight:%d", dog->name, dog->age, dog->weight);
    return info1;
};


int main()
{
    //方式1
    struct Dog dog = {"旺财", 2, 10};
    printf("dog info: %s\n", get_dog_info(dog));

    //方式2
    struct Dog *dog1 = &dog;
    //或
    char *Info = NULL;
    Info = get_dog_info1(dog1);
    printf("dog1 info: %s\n", Info);
    printf("dog1 info: %s\n", get_dog_info1(dog1));
    return 0;
}

案例二:

c 复制代码
#include <stdio.h>
#include <stdbool.h>
#include <string.h>  // 添加string.h头文件用于strcpy
//结构体指针

//方式 1 : 先定义结构体
struct Box
{
   double length;
   double width;
   double height;
};

double bulk(struct Box *box)
{
    return box->length * box->width * box->height; //使用结构体指针访问结构体成员
}



int main()
{
    //方式1
    struct Box box1;
    printf("请输入长、宽、高:\n");
    scanf("%lf %lf %lf", &box1.length, &box1.width, &box1.height);
    printf("体积 = %.2lf\n", bulk(&box1)); //使用结构体指针作为函数参数
    return 0;
}

案例三:

c 复制代码
#include <stdio.h>
#include <stdbool.h>
#include <string.h>  // 添加string.h头文件用于strcpy
//结构体指针

//方式2 : 在函数中定义结构体
struct Person
{
    char name[20];
    int age;
    double pay;
};

void print(struct Person *ptr)
{
    // printf("姓名:%s,年龄:%d,工资:%.2lf\n", p->name, p->age, p->pay); //使用结构体指针访问结构体成员
    ptr->pay =( ptr->age > 18) ? 3000 : 1000;
}


int main()
{
    //方式2
    struct Person ptr11;
    printf("请输入姓名、年龄\n");
    scanf("%s %d", &ptr11.name, &ptr11.age);

    print(&ptr11);
    struct Person *ptr = &ptr11;
    printf("姓名:%s ,年龄:%d ,工资:%.2lf \n", ptr->name, ptr->age, ptr->pay); //使用结构体指针访问结构体成员
    return 0;
}
相关推荐
charlie1145141914 分钟前
深入理解C/C++的编译链接技术6——A2:动态库设计基础之ABI设计接口
c语言·开发语言·c++·学习·动态库·函数
Cx330❀7 分钟前
C++ STL set 完全指南:从基础用法到实战技巧
开发语言·数据结构·c++·算法·leetcode·面试
white-persist10 分钟前
【攻防世界】reverse | Reversing-x64Elf-100 详细题解 WP
c语言·开发语言·网络·python·学习·安全·php
FeiHuo5651510 分钟前
微信个人号开发中如何高效实现API二次开发
java·开发语言·python·微信
zmzb010311 分钟前
C++课后习题训练记录Day33
开发语言·c++
csbysj202014 分钟前
Bootstrap 折叠
开发语言
Want59530 分钟前
C/C++贪吃蛇小游戏
c语言·开发语言·c++
豆浆whisky1 小时前
Go并发模式选择指南:找到最适合你项目的并发方案|Go语言进阶(19)
开发语言·后端·golang
草莓熊Lotso2 小时前
《算法闯关指南:动态规划算法--斐波拉契数列模型》--01.第N个泰波拉契数,02.三步问题
开发语言·c++·经验分享·笔记·其他·算法·动态规划
胖咕噜的稞达鸭2 小时前
自定义shell命令行解释器自制
java·开发语言