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

C语言结构体无法显示输入值,调用show方法后无报错直接退出

问题根因

你的程序触发了C语言的未定义行为,没有报错直接退出是内存访问越界的典型表现,具体错误点如下:

  • 结构体Book中的title成员定义为未初始化的char*指针,没有分配可供存储字符串的有效内存空间,直接写入输入内容会访问非法内存。
  • scanf输入参数错误:你对b[i].title使用了取地址符&,相当于把字符串写入了存储指针变量的内存区域,而非存储书名的目标空间,进一步破坏内存结构。
  • 类型匹配错误:price是short类型,scanf使用%d(对应int类型)格式符会导致数值存储异常。
修正代码(新手友好版,使用固定长度字符数组)
#include<stdio.h>
#include<string.h>

struct Book{
    // 改为固定长度字符数组,提前分配128字节存储空间
    char title[128];
    short price;
};

void show(struct Book b[],const short n){
    short i;
    printf("\nBOOK DETAILS");
    for(i=0;i<n;i++){
        printf("\nRecord no %d / %d",i+1,n);
        printf("\nTitle : %s \nPrice: %hd",b[i].title, b[i].price);
    }
}

void get(struct Book b[],const short n){
    short i;
    for(i=0;i<n;i++){
        printf("\nRecord no %d / %d",i+1,n);
        printf("\nEnter book title & price: ");
        // 修正参数:title是数组名本身就是地址,不需要&;%hd对应short类型
        scanf("%s %hd",b[i].title, &b[i].price);
    } 
    show(b,n);
}

int main()
{
    struct Book b[3];
    get(b,3);
    return 0;
}
补充说明

如果需要支持长度不固定的长书名,可以改为动态内存分配方案:保持结构体char *title的定义,在scanf前添加b[i].title = (char*)malloc(256);分配256字节空间,使用完毕后记得调用free()释放内存避免泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:36:03