通过指针访问struct时“无法转换为指针类型”

时间:2016-11-23 15:06:31

标签: c pointers struct

gcc -g -O2    struct.c   -o struct
struct.c: In function ‘secondfunction’:
struct.c:19:2: error: cannot convert to a pointer type
  firstfunction((void *)onedata->c,(void *)&twodata.c,2);
  ^~~~~~~~~~~~~
<builtin>: recipe for target 'struct' failed
make: *** [struct] Error 1

我正在尝试通过memcpy将struct的内容复制到另一个struct时使用指针。但是当我将指向结构的指针转换为函数时,我无法将其转换为void。

struct one {
    char a;
    char b;
};

struct two {
    struct one c;
    struct one d;
};

void firstfunction(void *source, void *dest, int size)
{
    //memcpy(dest,source,size)
}

void secondfunction(struct two *onedata)
{
    struct two twodata;
    firstfunction((void *)onedata->c,(void *)&twodata.c,2);
}

void main()
{
    struct two onedata;
    secondfunction(&onedata);
}

2 个答案:

答案 0 :(得分:5)

您错过了&符号(&):

 firstfunction(&onedata->c, &twodata.c,2);
               ^

(我删除了不必要的演员阵容)。

答案 1 :(得分:2)

你想要这个:

void secondfunction(struct two *onedata)
{
  struct two twodata;
  firstfunction(&onedata->c, &twodata.c, 2);
}

您忘记了&运营商。

顺便说一句:这里没有必要转发(void*)

相关问题