簡體   English   中英

結構初始化錯誤:初始化時類型不兼容

[英]structure initialization error: incompatible types when initializing

我在通過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等效於szHolder[0] ,因此這是一個char

與此相反, struct字段char szHolder[50]是一個數組。 數組不能由表達式初始化,它們迫切需要一個{ .. something .. }初始化器。 這類似於不能分配數組的事實。

但是,如果這確實是您得到的診斷消息,則不只是神秘的。

您可以按照此問題的答案之一中所述的方式填充Book struct

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM