分配时不兼容的类型

时间:2014-06-29 18:15:15

标签: c pointers

我有以下代码,我多次阅读和阅读它似乎总是没问题,但编译器说:

  

错误:分配到类型' struct类型[10]'时不兼容的类型   来自类型'类型'

这是代码:

#include <stdio.h>

typedef struct
{
    int a;
    int b;
} Type;

typedef struct
{
    Type (*typeArray)[10];
} Type2;


void someFunction(Type2 *type2Variable, Type (*typeArray)[10])
{
    Type typeNewValue;

    type2Variable->typeArray[0] = typeNewValue;  /* This throws the error */
}

int main(int argc, char **argv)
{
    Type typeArray[10];
    Type2 type2Variable;

    someFunction(&type2Variable, &typeArray);
}

我确定解决方案只是某处*,但我无法找到它。

更新

非常感谢您的回答,这只是一个显示我的问题的无意义的例子(这不是真正的代码)。

解决方案是:

(*type2Variable->typeArray)[0] = typeNewValue;

而不是:

type2Variable->typeArray[0] = typeNewValue;

4 个答案:

答案 0 :(得分:1)

Type (*typeArray)[10]向类型为Type的大小为10的数组声明指针。您似乎想要声明一个Type

的数组
typedef struct
{
  Type typeArray[10];
} Type2;

void someFunction(Type2 *type2Variable, Type * typeArray) { /* ... */ }

答案 1 :(得分:0)

您正在尝试分配一个Type,其中Type[10]是预期的,这正是编译器所抱怨的。您必须将Type2::typeArray成员从Type (*typeArray)[10];更改为Type typeArray[10];才能使该作业生效。

答案 2 :(得分:0)

您为参数选择的名称有助于混淆事物。
编写代码的方式,指示行上的错误

type2Variable->typeArray[0] = typeNewValue;  /* This throws the error */  

是因为它应该写成:

type2Variable->typeArray = typeArray;  /* to match argument name */   

请看这里的论点:

//                                             V-------V
void someFunction(Type2 *type2Variable, Type (*typeArray)[10])
{
    Type typeNewValue, *pTypeNewValue;

    pTypeNewValue = &typeNewValue;

    type2Variable->typeArray = typeArray; //No longer throws error 
}

答案 3 :(得分:0)

更改为

void someFunction(Type2 *type2Variable, Type (*typeArray)[10])
{
    Type typeNewValue;//uninitialized
    type2Variable->typeArray = typeArray;//maybe :) But for what.
    (*type2Variable->typeArray)[0] = typeNewValue;
}
相关问题