首页 > 解决方案 > C - 程序打印不正确

问题描述

我正在为动态内存分配而苦苦挣扎,我不知道下面代码的逻辑有什么问题。有人可以给我一个解释并改变什么是错的。

struct Books {
char *title = new char[0];
char *author;
int pages = 0;
int price = 0;
};

int main()
{

struct Books book;

/*char size = (char)malloc(sizeof(book.title));*/

printf("The title of the book is:\n");
fgets(book.title, sizeof(book.title), stdin);

printf("The title is:\n %s", book.title);

}

标签: c++memory

解决方案


以下是如何编写代码以使其合法 C

struct Books {
    char *title;
    char *author;
    int pages;
    int price;

};

int main()
{

    struct Books book;

    book.title = malloc(100);

    printf("The title of the book is:\n");
    fgets(book.title, 100, stdin);

    printf("The title is:\n %s", book.title);

}

这将在任何关于 C 的书籍中介绍,您真的应该阅读一本。


推荐阅读