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;
}
相关推荐
历程里程碑7 分钟前
C++ 17异常处理:高效捕获与精准修复
java·c语言·开发语言·jvm·c++
雨雨雨雨雨别下啦9 分钟前
ssm复习总结
java·开发语言
拾贰_C30 分钟前
【python | pytorch | 】.报错怎么找到问题所在?
开发语言·pytorch·python
JasmineWr33 分钟前
Java SPI和OSGi
java·开发语言
Lisonseekpan34 分钟前
@Autowired 与 @Resource区别解析
java·开发语言·后端
Dillon Dong34 分钟前
从C到Simulink:用Counter模块玩转嵌入式定时器
c语言·stm32·simulink
你的冰西瓜35 分钟前
C++中的vector容器详解
开发语言·c++·stl
刻BITTER36 分钟前
C++ 获取任意整数类型的最大、最小值和长度
开发语言·c++
宵时待雨1 小时前
C语言笔记归纳22:预处理详解
c语言·开发语言·笔记
superman超哥1 小时前
仓颉语言中循环语句(for/while)的深度剖析与工程实践
c语言·开发语言·c++·python·仓颉