C struct problem

2019-04-28 18:31发布

I am trying to learn about structs in C, but i do not understand why i cannot assign the title as i my example:

#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;
}

Error message:

books.c: In function ‘main’:
books.c:13: error: incompatible types when assigning to type ‘char[100]’ from type ‘char *’

标签: c struct
4条回答
成全新的幸福
2楼-- · 2019-04-28 18:45

LHS is an array, RHS is a pointer. You need to use strcpy to put the pointed-to bytes into the array.

strcpy(my_library.title, "Book Title");

Take care that you do not copy source data > 99 bytes long here as you need space for a string-terminating null ('\0') character.

The compiler was trying to tell you what was wrong in some detail:

error: incompatible types when assigning to type ‘char[100]’ from type ‘char *’

Look at your original code again and see if this makes more sense now.

查看更多
姐就是有狂的资本
3楼-- · 2019-04-28 19:00

As the message says, the issue is you are trying to assign incompatible types: char* and char[100]. You need to use a function like strncpy to copy the data between the 2

strncpy(my_library.title, "Book Title", sizeof(my_library.title));
查看更多
虎瘦雄心在
4楼-- · 2019-04-28 19:05

title is a character array - these are not assignable in C. Use strcpy(3).

查看更多
贼婆χ
5楼-- · 2019-04-28 19:07

char* and char[100] are different types.

You want to copy those char elements inside the .title buffer.

strncpy(my_library.title, "Book Title", sizeof(my_library.title));
查看更多
登录 后发表回答