gpt4 book ai didi

c - 结构初始化错误: incompatible types when initializing

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:39 26 4
gpt4 key购买 nike

我在通过 C 中的函数初始化结构时遇到问题,而且我似乎找不到这里的问题所在。以下是我的代码的相关部分:

struct Date
{
int nMonth;
int nDay;
int nYear;
};

struct Book
{
char szISBN[10];
char szTitle[75];
char szType[50];
char szPublisher[75];
int nPages;
float fPrice;
int nYearOfPub;
int nStatus;
char szHolder[50];
struct Date dueDate;
};

稍后,在我的一个函数中:

struct Book addNewBook(struct Book *pBooks, int nStock, struct tm *t)
{
char szISBN[10];
char szTitle[75];
char szType[50];
char szPublisher[75];
int nPages;
float fPrice;
int nYearOfPub;
int nStatus;
char szHolder[50];
struct Date dueDate = {t->tm_mon+1, t->tm_mday, t->tm_year+1900};//we will set this to be the current day by default

...

struct Book newBook = {*szISBN, *szTitle, *szType, *szPublisher, nPages, fPrice, nYearOfPub, nStatus, *szHolder, dueDate};
return newBook;
}

我一直收到这个看起来非常简单的错误,但似乎无法修复它。

error: incompatible types when initializing type 'char' using type 'struct Date'

除非我有阅读障碍,否则当我创建 Book 结构时程序顶部的数据类型与我稍后在程序中的方法中初始化新书的位置匹配得很好。我在这里错过了什么?怎么回事?

编辑:这是我使用的解决方案,感谢 REACHUS 链接了另一个帮助我找到解决方案的问题。

struct Book addNewBook(struct Book *pBooks, int nStock, struct tm *t)
{
...
struct Book newBook = {"", "", "", "", nPages, fPrice, nYearOfPub, nStatus, "", dueDate};
strncpy(newBook.szISBN, szISBN, 10);
strncpy(newBook.szTitle, szTitle, 75);
strncpy(newBook.szType, szType, 50);
strncpy(newBook.szPublisher, szPublisher, 75);
strncpy(newBook.szHolder, szHolder, 50);
return newBook;
}

最佳答案

*szHolder 在初始化器中相当于 szHolder[0],所以这是一个 char

与此相反,struct 字段 char szHolder[50] 是一个数组。数组不能用表达式初始化,它们必须有一个 { .. something .. } 初始化器。这类似于数组也不能赋值的事实。

但是,如果这真的是您收到的诊断信息,那它就不仅仅是神秘的了。

关于c - 结构初始化错误: incompatible types when initializing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com