gaaa515 2021-12-21 00:02 采纳率: 92.3%
浏览 23
已结题

请教关于动态内存分配问题,如果要用上malloc()函数应该如何做

在动态存储器中确保一个结构体的区域,确保完成后让用户输入结构体的信息。
使用AceStriker的结构体,如果无法确保区域,则printf输出错误消息
确保领域后,让用户输入选手名和得分数,保存到结构体中

问题相关代码,请勿粘贴截图
#include <stdio.h>
typedef struct {
    char name[50];
    int goalno;
} AceStriker;
AceStriker hattrick(AceStriker *);
int main() {
    AceStriker messi = {"Lionel Messi", 5};
    messi = hattrick(&messi);
    printf("%s scores a hattrick! New number of goals: %d.\n", messi.name, messi.goalno);
    return 0;
}
AceStriker hattrick(AceStriker *fw) {
    fw->goalno += 3;
    return *fw;
}


我想要达到的结果

输出结果为:

Fruit data before deleting
Code: 1008, Fruit: Apple, Price: 250
Code: 1005, Fruit: Banana, Price: 160
Code: 1009, Fruit: Kiwi, Price: 98
Code: 1013, Fruit: Grape, Price: 1650
Code: 1007, Fruit: Orange, Price: 180
Code: 1002, Fruit: Pineapple, Price: 298
Code: 1004, Fruit: Kaki, Price: 230
Code: 1010, Fruit: Nashi, Price: 370
Code: 1006, Fruit: Pear, Price: 270
Code: 1001, Fruit: Strawberry, Price: 400
*** Deleting fruit with barcode 1007 ***
Fruit data after deleting
Code: 1008, Fruit: Apple, Price: 250
Code: 1005, Fruit: Banana, Price: 160
Code: 1009, Fruit: Kiwi, Price: 98
Code: 1013, Fruit: Grape, Price: 1650
Code: 1002, Fruit: Pineapple, Price: 298
Code: 1004, Fruit: Kaki, Price: 230
Code: 1010, Fruit: Nashi, Price: 370
Code: 1006, Fruit: Pear, Price: 270
Code: 1001, Fruit: Strawberry, Price: 400
  • 写回答

2条回答 默认 最新

  • 关注

    你题目的解答代码如下:

    #include<stdio.h>
    #include<stdlib.h>
    typedef struct {
        char name[50];
        int goalno;
    } AceStriker;
    AceStriker hattrick(AceStriker *);
    int main() {
        AceStriker messi = {"Lionel Messi", 5};
        messi = hattrick(&messi);
        printf("%s scores a hattrick! New number of goals: %d.\n", messi.name, messi.goalno);
        return 0;
    }
    AceStriker hattrick(AceStriker *fw) {
        fw = (AceStriker *)malloc(sizeof(AceStriker));
        scanf("%s", fw->name);
        scanf("%d", &fw->goalno);
        return *fw;
    }
    
    

    如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月29日
  • 已采纳回答 12月21日
  • 创建了问题 12月21日

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊