You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言如何实现create_order函数创建预填充的Order结构体对象

C语言create_order函数实现示例

前置依赖对齐

默认你项目中的Date、Order结构体定义符合以下通用结构,若实际成员名有差异,只需对应修改赋值语句即可:

#include <stdio.h>
#include <string.h>

// 已定义的日期结构体
typedef struct {
    int year;
    int month;
    int day;
} Date;

// 已定义的订单结构体
typedef struct {
    int order_id;       // 订单编号
    Date order_date;    // 订单日期
    char customer[50];  // 客户名,数组长度按你实际定义调整即可
    double total_price; // 订单总价
} Order;

// 已实现的打印订单函数,此处为示例实现方便测试,可直接用你项目中已有的实现
void print_order(Order o) {
    printf("订单编号:%d\n", o.order_id);
    printf("订单日期:%d-%02d-%02d\n", o.order_date.year, o.order_date.month, o.order_date.day);
    printf("客户名称:%s\n", o.customer);
    printf("订单总价:%.2f\n", o.total_price);
}

create_order函数实现

Order create_order(int order_id, int year, int month, int day, const char* customer_name, double total_price) {
    // 声明本地Order变量
    Order new_order;

    // 填充订单编号
    new_order.order_id = order_id;

    // 填充订单日期字段
    new_order.order_date.year = year;
    new_order.order_date.month = month;
    new_order.order_date.day = day;

    // 填充客户名,使用strcpy拷贝字符串到结构体的char数组中
    strcpy(new_order.customer, customer_name);

    // 填充订单总价
    new_order.total_price = total_price;

    // 返回填充完成的Order对象
    return new_order;
}

测试验证示例

你可以在main函数中直接调用验证效果:

int main() {
    // 创建测试订单:编号1001,日期2024-05-20,客户张三,总价299.9
    Order o = create_order(1001, 2024, 5, 20, "张三", 299.9);
    // 调用已有的打印函数输出订单详情
    print_order(o);
    return 0;
}

注意:如果你的Order结构体中客户名字段是char*指针类型,需要额外调用malloc申请对应长度的内存存储字符串,避免访问野指针崩溃

内容的提问来源于stack exchange,提问作者yunnaming2006

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:36:06