【发布时间】:2017-05-24 02:50:17
【问题描述】:
当我使用 GCC 编译时,我有一个可以工作的 C 代码,但我试图找出代码是否可以正常工作,或者是因为 GCC 按照我的设计预期处理了该代码。
注意 我并不是要“修复”它。我正在尝试了解编译器
这是我所拥有的:
iexample.h
#ifndef IEXAMPLE_H_
#define IEXAMPLE_H_
/* The interface */
struct MyIf
{
int (* init)(struct MyIf* obj);
int (* push)(struct MyIf* obj, int x);
void (* sort)(struct MyIf* obj);
};
/* The object, can be in different header */
struct Obj1
{
struct MyIf myinterface;
int val1;
int val2;
};
struct Obj1* newObj1();
#endif
iexample.c
#include <stdio.h>
#include <stdlib.h>
#include "iexample.h"
/* Functions here are "equivalent" to methods on the Obj1 struct */
int Obj1_init(struct Obj1* obj)
{
printf("Obj1_init()\n");
return 0;
}
int Obj1_push(struct Obj1* obj, int x)
{
printf("Obj1_push()\n");
return 0;
}
void Obj1_sort(struct Obj1* obj)
{
printf("Obj1_sort()\n");
}
struct Obj1* newObj1()
{
struct Obj1* obj = malloc(sizeof(struct Obj1));
obj->myinterface.init = Obj1_init;
obj->myinterface.push = Obj1_push;
obj->myinterface.sort = Obj1_sort;
return obj;
}
main.c
#include "iexample.h"
int main(int argc, char* argv[])
{
struct MyIf* myIf = (struct MyIf*) newObj1();
myIf->init(myIf);
myIf->push(myIf, 3);
myIf->sort(myIf);
/* ... free, return ... */
}
当我编译时,正如我所料,我在 newObj1() 中分配指针,
warning: assignment from incompatible pointer type
只要我有“struct MyIf myinterface”作为结构的第一个成员,代码就可以工作,这是设计使然(我喜欢在脚上开枪)
现在,虽然我分配了不兼容的指针类型,并且 C 规范说行为未定义,但 GCC 或其他编译器是否对如何处理这种情况做出任何设计声明?我几乎可以发誓,由于结构内存的布局方式,这应该可以工作,但我找不到证据。
谢谢
【问题讨论】: