The problem with the C structure

I am trying to learn about structures in C, but I do not understand why I cannot assign a title as 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 *' 
+6
c struct
source share
4 answers

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

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

Make sure that you do not copy the original data> 99 bytes here, since you needed a place for the line terminator ('\ 0').

The compiler tried to tell you what was wrong in the details:

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

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

+9
source share

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

 strncpy(my_library.title, "Book Title", sizeof(my_library.title)); 
+6
source share

title is an array of characters - they cannot be assigned in C. Use strcpy(3) .

+3
source share

char * and char [100] are different types.

You want to copy these char elements to the .title buffer.

 strncpy(my_library.title, "Book Title", sizeof(my_library.title)); 
+1
source share

All Articles