-1

I am new to C programming and have a question. It's a simple programme but dont know why it gives such a compilation error.

#include<stdio.h>
#include<conio.h>
struct Book
{
 char book_name[20];
 char auther[20];
 int book_id;
};

void main()
{
struct Book b1;
clrscr();

 b1.book_name="c++"; 
 b1.auther="xyz";
 /* Above two line show compile time error Lvalue required */ 

 b1.book_id=1002;


printf("\n Book Name= %s",b1.book_name);
printf("\n Book Auther= %s",b1.auther);
printf("\n Book ID= %s",b1.book_id);


getch();
}
chrisaycock
  • 36,470
  • 14
  • 88
  • 125
uday
  • 1
  • 1
  • 3
    You can't assign arrays with `=` in C. Use `strcpy` and friends instead. – Eugene Sh. Jan 12 '17 at 16:01
  • But you can *initialize* a `char` array with a string constant. This problem (as posed) could be addressed by declaring `b1` with an initializer; `strcpy()` would not be needed in that case. – John Bollinger Jan 12 '17 at 16:11

1 Answers1

2

C doesn't allow assignment from a string ("c++") to a char array (book_name). Instead, you'll need to copy the contents:

strcpy(b1.book_name, "c++");

Of course, this assumes that book_name is big enough to contain the contents. You can look into strncpy() to prevent overwriting your buffer once you get comfortable with the above.

chrisaycock
  • 36,470
  • 14
  • 88
  • 125