【问题标题】:"cannot convert to a pointer type" with accessing struct via pointer通过指针访问结构时“无法转换为指针类型”
【发布时间】:2016-11-23 15:06:30
【问题描述】:
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 将结构的内容复制到另一个结构时使用指针。但是,当我将指向结构的指针转换为函数时,我无法将其转换为 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);
}

【问题讨论】:

  • 附带说明,使用void main() 而不是int main() 通常被认为是不好的形式
  • 不要在没有必要的情况下使用void *。并且不要投向或投向void *

标签: c pointers struct


【解决方案1】:

您缺少一个 & 符号 (&amp;):

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

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

【讨论】:

    【解决方案2】:

    你想要这个:

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

    您只是忘记了&amp; 运算符。

    顺便说一句:这里不需要转换为(void*)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2016-05-05
      • 1970-01-01
      • 2020-10-21
      • 2011-02-03
      相关资源
      最近更新 更多