Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing the 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 the lengths of the types may be different.

but is there anything wrong with adding annother layer of indirection:

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

My thinking behind this: The pointer to the function pointer should be pointing to data memory and therefore should have the same length as the void* type.

So how wrong am I?

like image 530
jayjay Avatar asked May 20 '15 13:05

jayjay


1 Answers

You are right that all pointer types are object types:

N1570 6.3.5 Types, paragraph 20, fifth list item:

  • A pointer type may be derived from a function type or an object type, called the referenced type. A pointer type describes an object whose value provides a reference to an entity of the referenced type. A pointer type derived from the referenced type T is sometimes called ‘‘pointer to T’’. The construction of a pointer type from a referenced type is called ‘‘pointer type derivation’’. A pointer type is a complete object type.

But pointers to object types don't necessarily have same size as void* (6.2.5 p28).

  1. A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

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

  1. A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
like image 196
user694733 Avatar answered Nov 08 '22 22:11

user694733