【问题标题】:"Assignment from incompatible pointer type" warning“来自不兼容的指针类型的分配”警告
【发布时间】:2012-01-06 09:18:42
【问题描述】:

我正在编写一个函数,它解析带有纹理和动画数据的文件并将其加载到我声明的一些全局结构中。我在特定行上收到编译器警告“来自不兼容的指针类型的赋值”。代码很多,这里只贴重要部分。

首先,我的动画例程有一个结构数据类型,如下所示:

    typedef struct {
        unsigned int frames;
        GLuint *tex;
        float *time;
        struct animation *next;
    } animation;

如您所见,结构体中的最后一个变量是指向另一个动画的指针,默认指向动画完成的时间。

这里是加载函数的声明:

    void LoadTexturePalette(GLuint **texture, animation **anim, const char *filename)

该函数将信息加载到动画数组中,因此是双指针。

在加载每个动画的最后,从文件中提取一个整数,指示“下一个”指针将指向哪个动画(在加载的动画中)。

    fread(tmp, 1, 4, file);
    (*anim)[i].next = &((*anim)[*tmp]);

在最后一行,我收到编译器警告。我还没有使用那个变量,所以我不知道警告是否是一个问题,但我觉得我的语法或方法在设置该变量时可能不正确。

【问题讨论】:

  • (*anim)[i].next 是指向struct animation 的指针; &((*anim)[*tmp]) 是一个animation 的地址,一个没有标签的struct

标签: c pointers struct warnings


【解决方案1】:
   typedef struct { /* no tag in definition */
       unsigned int frames;
       GLuint *tex;
       float *time;
       struct animation *next; /* pointer to an undefined structure */
   } animation;

如果没有标签 (typedef struct animation { /* ... */ } animation;),任何在结构定义中对“结构动画”的引用都是对一个尚未定义的结构的引用。由于您只使用指向该未定义结构的指针,因此编译器不会介意。

所以,添加标签 --- 甚至可能去掉 typedef:它只会增加混乱:)

    typedef struct animation { /* tag used in definition */
        unsigned int frames;
        GLuint *tex;
        float *time;
        struct animation *next; /* pointer to another of this structure */
    } animation;

【讨论】:

  • 多么完美的解释!这立即解决了问题!谢谢!
  • 我不一定会说 typedef 会增加混乱,因为它的目的是删除其余代码中的混乱,但我认为它们通常被过度使用。我发现使用 struct 关键字时代码更易于阅读,尤其是在没有针对自定义类型的智能语法突出显示的编辑器中。
猜你喜欢
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多