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;
}
相关推荐
Bdygsl6 分钟前
前端开发:JavaScript(6)—— 对象
开发语言·javascript·ecmascript
2301_7850381811 分钟前
c++初学day1(类比C语言进行举例,具体原理等到学到更深层的东西再进行解析)
c语言·c++·算法
babytiger37 分钟前
我的c#用到Newtonsoft.Json.dll,Fleck.dll这两个dll能否打到一个exe 中,而不是一起随着exe拷贝
开发语言·c#·json
How_doyou_do1 小时前
睿抗开发者大赛国赛-24
开发语言·python
BrownMox2 小时前
CORS 跨域问题 Next.js 跨域问题放通
开发语言·javascript·ecmascript
JasmineX-13 小时前
STM32的SPI通信(软件读写W25Q64)
c语言·stm32·单片机·嵌入式硬件
zhysunny3 小时前
Python从入门到精通计划Day07: Python数据卷轴术:文件魔法与防御结界全指南
开发语言·python
##学无止境##4 小时前
深入剖析Java线程:从基础到实战(上)
java·开发语言·redis
大雷神6 小时前
站在JS的角度,看鸿蒙中的ArkTs
开发语言·前端·javascript·harmonyos
Bdygsl7 小时前
前端开发:JavaScript(3)—— 选择与循环
开发语言·javascript·ecmascript