我已阅读了本书了解和使用C指针,并尝试编译下面的代码。但是在编译之后我得到了警告:从不兼容的指针类型中分配。
我检查了代码并找出函数指针fptrSet
并且函数ShapeSetX
不兼容,因为fptrSet的第一个参数是void *
而函数ShapeSetX是Shape *
。
我该如何解决这个问题? 谢谢!
typedef void (*fptrSet)(void*, int);
typedef int (*fptrGet)(void*);
typedef void (*fptrDisplay)();
typedef struct _vfunc
{
fptrSet setX;
fptrGet getX;
fptrSet setY;
fptrGet getY;
fptrDisplay display;
} vFunc;
typedef struct _shape
{
vFunc function;
int x;
int y;
} Shape;
void displayShape(){
printf("Shape\n");
}
void ShapeSetX(Shape *shape, int x){
shape->x = x;
}
void ShapeSetY(Shape *shape, int y){
shape->y = y;
}
int ShapeGetX(Shape *shape){
return shape->x;
}
int ShapeGetY(Shape *shape){
return shape->y;
}
Shape *newShape()
{
Shape *shape = (Shape *)malloc(sizeof(Shape));
shape->x = 10;
shape->y = 10;
shape->function.setX = ShapeSetX;
shape->function.getX = ShapeGetX;
shape->function.setY = ShapeSetY;
shape->function.getY = ShapeGetY;
shape->function.display = displayShape;
return shape;
}
答案 0 :(得分:1)
你必须尊重指针定义:指针需要第一个参数是一个指向void的指针,所以你的函数实现应该有第一个参数为void:
void ShapeSetX(void *void_shape, int x){
Shape *shape = (Shape*) void_shape;
shape->x = x;
}
void ShapeSetY(void *void_shape, int y){
Shape *shape = (Shape*) void_shape;
shape->y = y;
}
int ShapeGetX(void *void_shape){
Shape *shape = (Shape*) void_shape;
return shape->x;
}
int ShapeGetY(void *void_shape){
Shape *shape = (Shape*) void_shape;
return shape->y;
}
答案 1 :(得分:1)
我打算说“为什么不用void
替换Shape
?”,直到我意识到Shape
尚未定义 - 你也不能交换这两个定义,因为Shape
需要vFunc
,需要typedef
s。
所以,这样做:
typedef struct _shape Shape; // Define _shape and Shape later
typedef void (*fptrSet)(Shape*, int);
typedef int (*fptrGet)(Shape*);
typedef void (*fptrDisplay)();
如果编译器不喜欢,您可能需要将其更改为:
typedef struct _shape; // Define _shape later
typedef void (*fptrSet)(struct _shape*, int);
typedef int (*fptrGet)(struct _shape*);
typedef void (*fptrDisplay)();