Saving a pointer to a function pointer in a void *

I understand why you cannot do:

void(*fp)(void) = &function; function_taking_void_pointer((void*)fp); 

because type lengths can be different.

but is there something wrong with the addition of a second layer of indirection:

 void(*fp)(void) = &function; void(**fpp)(void) = &fp; function_taking_void_pointer((void*)fpp) 

I think about this: a pointer to a function pointer must point to data memory and therefore must be the same length as the void * type.

So how am I wrong?

+6
source share
2 answers

You are right that all types of pointers are types of objects:

N1570 6.3.5 Types, clause 20, fifth element of the list:

  • A pointer type can be obtained from a function type or an object type called a reference type. A pointer type describes an object whose value gives a reference to an object of a reference type. A pointer type obtained from a reference type T is sometimes called a "pointer" to T. A pointer type construction from a reference type is called a "pointer type inference". The type of pointer is the full type of the object.

But pointers to object types are not necessarily the same size as void* (6.2.5 p28).

  1. A pointer to a void must have the same presentation and alignment requirements as a pointer to a character type. 48) Similarly, pointers to qualified or unqualified versions of compatible types must have the same presentation and alignment requirements. All pointers to structure types must have the same presentation and alignment requirements as each other. All pointers to types of trade unions should have the same presentation and harmonization of requirements with each other. Pointers to other types need not have the same presentation or alignment requirements.

However, all of them can be converted to void* (6.3.2.3 p1):

  • A pointer to void can be converted to or from a pointer to any type of object. A pointer to any type of object can be converted to a pointer to void and vice versa; The result should compare with the original pointer.
+4
source

This piece of code is incorrect.

     void (* fp) (void) = & function;
     function_taking_void_pointer ((void *) fp);

In C / C ++, the function name will be transferred to a specific address in the linking stage , so you cannot use & until the function name . In addition, function name not a variable in C / C ++, so you also cannot try to get its address.

-5
source

Source: https://habr.com/ru/post/987575/


All Articles