简体   繁体   English

如何为结构中的函数指针成员分配值

[英]How can I assign values to a function pointers members in a structure

struct a
{
  int (*ptr1)();
  int (*ptr2)();
  int data;
};

typedef struct
{
  struct a x;
}all;

int fun1()
{
  return 5;
};

int fun2()
{
  return 9;
};

I can assign like 我可以分配像

all *mem = (all*)malloc(sizeof(all));

mem->x.ptr1 = fun1;
mem->x.ptr2 = fun2;

Is there any other way to assign these function pointers? 还有其他方法可以分配这些函数指针吗? Is it possible to assign like this? 可以这样分配吗?

all *mem;

(void **)mem->ptr1[0] = fun1; 
(void **)mem->ptr2[1] = fun2;

No, this is not possible (I assume you actually meant the following, since your code doesn't make much sense) 不,这是不可能的(我假设您实际上是指以下内容,因为您的代码没有多大意义)

((void **)&mem->ptr1)[0]=fun1;
((void **)&mem->ptr1)[1]=fun1;

This is syntactically correct, but quoting the C standard: 这在语法上是正确的,但是引用了C标准:

There may be unnamed padding within a structure object, but not at its beginning. 结构对象内可能存在未命名的填充,但在其开始处没有。

which means you are not guaranteed that ((void **)&mem->ptr1)+1 == ((void **)&mem->ptr2) . 这意味着您无法保证((void **)&mem->ptr1)+1 == ((void **)&mem->ptr2)

The statement you posted 您发布的声明

(void **)mem->ptr1[0] = fun1;

actually means 实际上意味着

(void **)((mem->ptr1)[0]) = fun1;

which tries to index a function-pointer. 试图索引一个功能指针。

Note that all references like mem->ptr1 etc. should actually be mem->x.ptr1 according to your definitions. 请注意,根据您的定义,所有类似mem->x.ptr1 mem->ptr1等的引用实际上应该是mem->x.ptr1

No, you can't assign like this for many reasons: 不,由于多种原因,您不能像这样进行分配:

  1. function pointers are not compatible with void* . 函数指针与void*不兼容。 your compiler may allow this but this is undefined behavior according to the standard 您的编译器可能允许这样做,但这是根据标准的未定义行为
  2. By using [0] and [1] you are doin't pointer arithmetic on a void pointer, which isn't allowed either. 通过使用[0][1]您不会对void指针进行指针算术运算,这也是不允许的。

Also in your first example which works, you assign a pointer to a function. 同样在第一个可行的示例中,您将指针分配给函数。 This is ok as you did, since a function if you don't put () after it evaluates to its address. 就像您所做的一样,这是可以的,因为如果您不将()放在函数的末尾,则该函数将返回其地址。 But still I find it clearer to write &f in such case. 但是我仍然发现在这种情况下写&f更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM