![](/img/trans.png)
[英]“incompatible types when initializing type” after initializing an struct with an union inside
[英]error: incompatible types when initializing type 'struct ...'
我有以下代碼:
#include "stdio.h"
typedef struct StackEntry StackEntry;
typedef struct StackEntry
{
int data;
StackEntry *next;
};
StackEntry* createStack()
{
return NULL;
}
int main()
{
StackEntry *stack = createStack(); //Error: incompatible types when initializing type 'struct StackEntry *' using type 'StackEntry'
}
incompatible types when initializing type 'struct StackEntry *' using type 'StackEntry'
出現錯誤incompatible types when initializing type 'struct StackEntry *' using type 'StackEntry'
如上所示。 很長一段時間后,我正在重新訪問 C。 我在這里做錯了什么?
編輯(超級抱歉)
我不必要地簡化了東西。 我覺得這將有助於突出錯誤代碼。 我的原始設置有很多代碼。 它也在工作。 但現在它壞了。 所以我收集了所有相關的代碼並放在這里。 我應該首先嘗試將它們全部放在一個文件中並運行。 我很抱歉沒有這樣做。 但是現在我已經剝離了所有可能的代碼並能夠重現錯誤。 這里是:
算法.h
#ifndef ALGORITHMS_H_
#define ALGORITHMS_H_
StackEntry createStack();
#endif /* ALGORITHMS_H_ */
數據結構.h
#ifndef DATASTRUCTURES_H_
#define DATASTRUCTURES_H_
typedef struct StackEntry StackEntry;
struct StackEntry
{
int data;
StackEntry *next;
};
#endif /* DATASTRUCTURES_H_ */
堆棧文件
#include "datastructures.h"
#include "stdio.h"
StackEntry* createStack()
{
return NULL;
}
主文件
#include "datastructures.h"
#include "algorithms.h"
int main()
{
StackEntry *stack = createStack(); //Error: incompatible types when initializing type 'struct StackEntry *' using type 'StackEntry'
return 0;
}
您需要修復algorithms.h
:
#ifndef ALGORITHMS_H
#define ALGORITHMS_H
extern StackEntry *createStack();
#endif /* ALGORITHMS_H */
( extern
不是強制性的,這是一個很好的做法,但你確實需要這個*
)。
下面的代碼編譯正常 - 希望這會有所幫助(VSTO 2013 控制台應用程序)
#include "stdafx.h"
typedef struct StackEntry
{
int data;
StackEntry *next;
};
StackEntry* createStack()
{
return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
StackEntry *stack = createStack();
return 0;
}
正如您在評論中所說您正在使用 Eclipse,我認為 Eclipse 試圖比往常更聰明......
此代碼可能會發出警告(警告:typedef 需要名稱 [-Wmissing-declarations] ,因為正如@GrzegorzSzpetkowski 所解釋的那樣,您的第二個typedef
不包含名稱,因此忽略了 typedef。
但這足以干擾 Eclipse 迷路並顯示不存在的錯誤。
StackEntry
太多。 你可以這樣做:
struct _StackEntry; // there is such a struct, no matter where.
struct _StackEntry {
int a;
_StackEntry *next; // now the compiler knows that this is a valid type
}
typedef _StackEntry StackEntry; // add an alias of this type
我不知道這是否是答案。 我希望我能發表評論,但不幸的是,我只是這個網站的新手。 我會嘗試從您的結構定義中刪除 typedef:
typedef struct StackEntry StackEntry;
struct StackEntry
{
int data;
StackEntry *next;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.