C中数据结构赋值的类型不兼容

时间:2014-07-07 20:49:43

标签: c pointers matrix struct typedef

我编译项目时收到此错误。

error: incompatible types when assigning to type ‘Matrix4’ from type ‘double (*)[4]’

我的结构是这样的:

typedef struct testtest {
    Matrix4 tMat;
} test;

使用全局变量:

typedef double Matrix4[4][4];

现在,我在程序内部为结构的相关参数分配一个参数,如下所示:

test *newNode;
newNode = (test *)malloc(sizeof(test));
Matrix4 transformMatrix;
//inizializing the matrix....
//...
newNode->tMat = transformMatrix;  //<----HERE is the ERROR

此外,如果我将结构更改为:

typedef struct testtest {
    double tMat[4][4];
} test;

我收到类似的错误:

error: incompatible types when assigning to type ‘double[4][4]’ from type ‘double (*)[4]’

有谁知道我错在哪里?非常感谢你: - )

5 个答案:

答案 0 :(得分:1)

当数组名称是表达式的一部分时,它通常会衰减指向第一个元素,除非是sizeof或一元&运算符的操作数。 newNode->tMat的类型为double[4][4]transformMatrix在分配给newNode->tMat时,会转换为指向其第一个元素的指针,即double (*)[4]类型。

答案 1 :(得分:1)

您可以做两件事:

  1. tMat指向Matrix4

    typedef struct testtest {
        Matrix4 *tMat;
    } test;
    
    newNode->tMat = &transformMatrix;
    
  2. 使用memcpy

    memcpy(newNode->tMat, transformMatrix, sizeof(newNode->tMat));
    

答案 2 :(得分:1)

C对数组对象与其他所有 1 的处理方式不同,因此您无法使用=运算符将一个数组的内容分配给另一个数组; IOW

T src[N], dest[N];
...
dest = src;

无效。

要将一个(非字符串)数组的内容复制到另一个(非字符串)数组,请使用memcpy库函数:

memcpy( dest, src, sizeof dest );

对于字符串,请使用strcpystrncpy函数。

strcpy( dest, src );
strncpy( dest, src, sizeof dest - 1 );

<小时/> 1。除非它是sizeof或一元&运算符的操作数,或者是用于在声明中初始化另一个数组的字符串文字,否则类型为“N元素数组{{1 “将转换为类型为”T指针“的表达式,表达式的值将是数组中第一个元素的地址。生成的表达式不是可修改的左值,因此不能用作赋值的目标。请阅读this essay,特别是标有“胚胎C”的部分,了解原因。

答案 3 :(得分:1)

C中的数组不是first-class data types,并且不能出现在作业的任何一侧。

您可以指定一个指向数组的指针(零复制引用 - 不移动数据),您可以执行逐字节复制。如果元素本身是第一类类型,您还可以执行逐元素复制。

结构是第一类类型,因此您可以将数组包装在结构中并直接赋值,因此在您的情况下:

test transformMatrix;
//inizializing the matrix....
//...
*newNode = transformMatrix;

是有效的。

答案 4 :(得分:0)

我解决了,我无法从尚未创建的字段中复制内存。 memcpy工作,但只有当我使用不同的节点时,newNode才用于临时(使用malloc为它分配内存)。 所以像这样:

test *newNode;
test *recur;
newNode = (test *)malloc(sizeof(test));
Matrix4 transformMatrix;
//inizializing the matrix....
//...
memcpy(recur->tMat, transformMatrix, sizeof(newNode->tMat));

这很有效。谢谢大家让我了解新事物: - )