简体   繁体   English

结构不显示在 C 中输入的值

[英]Structure not displaying entered values in C

I'm trying to print the entered values from struct.我正在尝试从 struct 打印输入的值。 Program is able to get all input values but after show() method call it does jumps out of the program in exit without displaying my entered values.程序能够获取所有输入值,但在调用 show() 方法后,它会在退出时跳出程序而不显示我输入的值。

I'm not getting any error or warning at all.我根本没有收到任何错误或警告。

Code:代码:

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

struct Book{
    char *title;
    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); //exits after displaying this line
        printf("\nTitle : %s \nPrice: %d",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: ");
        scanf("%s %d",&b[i].title, &b[i].price);
    } 
    show(b,n);
}

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

Call sequence is like main() --> get() -->show().调用顺序类似于 main() --> get() -->show()。 I'm using Dev cpp compiler with .c extension of my code file.我正在使用 Dev cpp 编译器和我的代码文件的 .c 扩展名。

title member of struct Book is just a pointer to char * , so when you define a struct Book structure, no memory has been allocated for its title . struct Book title成员只是一个指向char *的指针,因此当您定义struct Book结构时,没有为其title分配内存。
Either define title as an array or allocate memory for it.title定义为数组或为其分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM