【发布时间】:2015-01-13 19:12:25
【问题描述】:
我在通过 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;
}
【问题讨论】:
-
什么是
struct tm? -
@REACHUS: struct tm 包含在
中,我只是在这里使用它来获取系统日期。
标签: c data-structures compiler-errors initialization