简体   繁体   English

C struct问题

[英]C struct problem

I am trying to learn about structs in C, but i do not understand why i cannot assign the title as i my example: 我试图在C中学习结构,但我不明白为什么我不能像我的例子那样分配标题:

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

LHS is an array, RHS is a pointer. LHS是一个数组,RHS是一个指针。 You need to use strcpy to put the pointed-to bytes into the array. 您需要使用strcpy将指向的字节放入数组中。

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. 请注意,此处不要复制> 99字节长的源数据,因为您需要空格来终止字符串终止的空('\\ 0')字符。

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 *' 错误:从类型'char *'分配类型'char [100]'时出现不兼容的类型

Look at your original code again and see if this makes more sense now. 再看看你的原始代码,看看现在是否更有意义。

As the message says, the issue is you are trying to assign incompatible types: char* and char[100] . 正如消息所述,问题是您正在尝试分配不兼容的类型: char*char[100] You need to use a function like strncpy to copy the data between the 2 您需要使用类似strncpy的函数来复制2之间的数据

strncpy(my_library.title, "Book Title", sizeof(my_library.title));

title是一个字符数组 - 这些不能在C中赋值。使用strcpy(3)

char* and char[100] are different types. char *和char [100]是不同的类型。

You want to copy those char elements inside the .title buffer. 您想要在.title缓冲区中复制这些char元素。

strncpy(my_library.title, "Book Title", sizeof(my_library.title));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM