我是 C 编程新手,有一个问题。这是一个简单的程序,但不知道为什么会出现这样的编译错误。
#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();
}
最佳答案
C 不允许将字符串 ("c++"
) 赋值给字符数组 (book_name
)。相反,您需要复制内容:
strcpy(b1.book_name, "c++");
当然,这假设 book_name
足够大以包含内容。一旦您熟悉了上述内容,您可以查看 strncpy()
以防止覆盖缓冲区。
关于c - 如何在main函数中初始化结构体对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41617698/