C struct问题

pet*_*n80 6 c struct

我试图在C中学习结构,但我不明白为什么我不能像我的例子那样分配标题:

#include <stdio.h>

struct book_information {
 char title[100];
 int year;
 int page_count;
}my_library;


main()
{

 my_library.title = "Book Title"; // Problem is here, but why?
 my_library.year = 2005;
 my_library.page_count = 944;

 printf("\nTitle: %s\nYear: %d\nPage count: %d\n", my_library.title, my_library.year, my_library.page_count);
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

books.c: In function ‘main’:
books.c:13: error: incompatible types when assigning to type ‘char[100]’ from type ‘char *’
Run Code Online (Sandbox Code Playgroud)

Ste*_*end 9

LHS是一个数组,RHS是一个指针.您需要使用strcpy将指向的字节放入数组中.

strcpy(my_library.title, "Book Title");
Run Code Online (Sandbox Code Playgroud)

请注意,此处不要复制> 99字节长的源数据,因为您需要空格来终止字符串终止的空('\ 0')字符.

编译器试图在某些细节上告诉你错误:

错误:从类型'char*'分配类型'char [100]'时出现不兼容的类型

再看看你的原始代码,看看现在是否更有意义.

  • 建议使用`strncpy`而不是`strcpy`来确保你没有超过数组大小限制. (2认同)

Jar*_*Par 6

正如消息所述,问题是您正在尝试分配不兼容的类型:char*char[100].您需要使用类似于strncpy在2之间复制数据的函数

strncpy(my_library.title, "Book Title", sizeof(my_library.title));
Run Code Online (Sandbox Code Playgroud)

  • `sizeof(my_library.title)-1`,不是吗? (2认同)