c++ - 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
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 的书籍中介绍,您真的应该阅读一本。
推荐阅读
- sql-server - MS Access:如何使用特定国家/地区的日期查询指定 ODBC 连接字符串?
- python - 我是否必须再次预处理新数据才能预测模型?
- javascript - Javascript:encodeURIComponent 返回在键盘中键入的值和从剪贴板粘贴的值之间的不同值
- android - 禁用 Android TV 上的默认焦点行为
- azure - 逻辑应用:使用另一个帐户发送邮件
- javascript - 将 knex 与 es6 模块一起使用
- git - Git 存储库:文件未反映最新提交
- javascript - 如何在 vue/nuxt 中导入几十个 svg 文件
- java - 为什么我的代码中不断出现 arrayIndexOutOfBound 异常错误
- nginx - Nginx、nuxt.js 静态生成模式和尾部斜杠重定向