错误(不兼容类型)初始化结构阵列时, [英] Error (incompatible types) when initialising struct array
问题描述
我读过这一些类似的问题,但我仍然无法看到我要去哪里错了。
我的malloc的指针和,似乎工作不错,但我得到这一行的错误(不兼容类型):
canArray [I] =(TinCan *)malloc的(的sizeof(TinCan))
下面是完整的code:
typedef结构TinCan
{
INT日期;
INT时间;
} 锡罐;诠释的main()
{
INT I;
TinCan * canArray =的malloc(10 * sizeof的(TinCan)); 对于(i = 0; I< 9;我++)
{
canArray [I] =(TinCan *)malloc的(的sizeof(TinCan));
}
}
猜你有一个 typedef结构{...} TinCan;
的地方,那么在这里:
TinCan * canArray =的malloc(10 * sizeof的(TinCan));
您有10 TinCan
结构足够的空间,但在这里:
canArray [I] =(TinCan *)malloc的(的sizeof(TinCan));
您正试图分配给另一个 TinCan
结构的空间。
你想要的:
-
TinCan
组成的数组?如果是这样,你不需要循环 - 空间已被分配,当你问10 * sizeof的(TinCan)
-
指针数组为
TinCan
结构?如果是这样,第一行更改为:TinCan ** canArray =的malloc(10 * sizeof的(canArray [0]));
和保持循环。
一些一般性的评论:
-
您不需要
malloc的前投()
通话 - 看 - 的我投malloc的结果? -
这是很好的做法是使用
的sizeof(varname的[0])
,而不是的sizeof(类型名称)
,以避免(或作出更明显)愚蠢的错误。 -
通过电流回路code,您将离开最后一个
TinCan
未初始化 - 你创建的canArray 10项
,但只初始化其中9I< 9
。更改为I< 10
,或额外的信用,换出既为的#define NUMBER_OF_CANS 10
I've read some similar questions to this but I still can't see where I'm going wrong.
I malloc the pointers and that seems to work OK, but I get an error (incompatible types) on this line:
canArray [i] = (TinCan *) malloc(sizeof(TinCan))
Here is the complete code:
typedef struct TinCan
{
int date;
int time;
} TinCan;
int main ()
{
int i;
TinCan *canArray = malloc(10 * sizeof(TinCan));
for (i =0; i < 9; i++ )
{
canArray [i] = (TinCan *) malloc(sizeof(TinCan));
}
}
Guessing that you have a typedef struct {...} TinCan;
somewhere, then here:
TinCan *canArray = malloc(10 * sizeof(TinCan));
You have enough space for 10 TinCan
structures, but here:
canArray [i] = (TinCan *) malloc(sizeof(TinCan));
You are trying to allocate space for another TinCan
struct.
Do you want:
An array of
TinCan
s? If so, you don't need the loop - the space has already been allocated when you asked for10 * sizeof(TinCan)
An array of pointers to
TinCan
structs? If so, change the first line to:TinCan **canArray = malloc(10 * sizeof(canArray[0]));
and keep the loop.
Some general comments:
You don't need the cast before the
malloc()
call - see - Do I cast the result of malloc?It's good practice to use
sizeof(varname[0])
rather thansizeof(typename)
, to avoid (or make more obvious) silly mistakes.With the current loop code, you will leave the last
TinCan
uninitialised - you're creating 10 entries incanArray
, but only initialising 9 of them withi < 9
. Change that toi < 10
, or for extra credit, swap out both for a#define NUMBER_OF_CANS 10
这篇关于错误(不兼容类型)初始化结构阵列时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!