c - 如何在main函数中初始化结构体对象?

标签 c

我是 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/

相关文章:

java - JNI 引用表溢出 : how to release ObjectArray containing Strings

用于从ubuntu服务器获取centOS服务器日期时间的C程序?

python - 将从网络数据包接收到的字符串数据转换为结构

将增量为 25 的 'for' 循环从 C 转换为 MATLAB

C rename() FileNotFound 尽管文件存在

C/C++ 如何将 int 转换回字符串(一个单词)?

c - 网络编程常用的函数/代码片段有哪些?

c - C 中的链表

c++ - 将 C++ 编译器添加到 Eclipse C 项目

c - 定义移位操作的临时结果如何存储是C标准吗?