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的书中,你真的应该读一本。

通常有两种方法可以处理这样的情况:您可以使用预定义大小的char数组,在这种情况下,您必须确保写入的字符数不会超过数组所能容纳的字符数。具有预定义大小数组的代码如下所示:

struct Books {
char title[255];
char author[255];
int pages;
int price;
};
int main()
{
struct Books book;
printf("The title of the book is:n");
fgets(book.title, sizeof(book.title), stdin);
printf("The title is:n %s", book.title);
}

在上面的情况下,使用sizeof(book.title(是有效的,因为在编译时大小是已知的。但"标题"永远不能超过254个字符。

另一种方法是使用动态内存分配:

struct Books {
char * title;
char * author;
int pages;
int price;
};
int main()
{
struct Books book;
book.title = NULL;
size_t n = 0;
printf("The title of the book is:n");
getline(&book.title, &n, stdin);
printf("The title is:n %s", book.title);
free(book.title);
}

在这种情况下,getline((函数为您分配内存,因此没有预定义的字符串最大大小。但是您必须自己释放它,并且不能使用sizeof((来获取数组的大小。

最新更新