6

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 *’

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, after adding "#include <strings.h>" the program compiles and works as expected. All examples i have found, has been using scanf or gets to fill the strings, and this makes sense to me now.
Thanks Peter. I would consider the strncpy alternatives, unless you are sure your input data will always be small enough to fit.
Though including strings.h may happen to work on your implementation, you really should be including string.h to declare strcpy.
Would recommend using strncpy over strcpy to make sure you're not going over array size limit.
I was going over structures today, and I came across the same problem. Of course, this solved my answer. But I don't see the logic behind it. Can someone explain why didn't C allow to equate a char array with a char pointer? After all, a pointer to an array is the first element of the array itself.
6

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));

2 Comments

sizeof(my_library.title)-1, no?
@Oli, indeed. Mentally smacked myself for the over site.
3

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

Comments

1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.