Void ** without temporary variable

I have a function with a prototype like this:

ErrorType function(void ** parameter, other_args);

      

This function reads the pointer pointed to by the "parameter" and changes it (think of it like realloc).

Now, to be correct according to the C standard, if I want to pass the address of a pointer other than void *, I have to declare a temporary variable void * and use it instead.

So, I want to create wrappers (I don't care if it's a function or a macro) that make a function call with any type of pointer.

I think I could do it in C11 with _Generic and a function for every base type, and a function for all structures, and a function for all unions, but I think it's too troublesome.

I also read about an extension to GCC that allows you to write statements and declarations in expressions, and I think I can easily do what I want with that, but I prefer my code to compile in all standard compilers, not just GCC or Clang.

So the question is, is there a way to do this without too much trouble in the C11 compiler?

+3


source to share


1 answer


If I understand the question correctly, you would like it to function

be able to change different types of pointers. Well, there's bad news and good news about it.

Bad news. The object representation of pointers is opaque, so you will need to tell your function

which pointer it should work with if your function is not guaranteed to copy the object's representation from the source pointer and you know that both representations have the same value.

For example, it sizeof (double *)

may differ fromsizeof (void *)



Good news. A pointer to any object type can be added to void *

and back, which consists void **

and double **

any other types of pointers. Thus, you could:

ErrorType function(void * ptr, int ptr_type, ...) {
    void ** vpp;
    double ** dpp;
    ...

    ...
    switch (ptr_type) {
        case PTR_TYPE_VOIDP:
        vpp = ptr;
        /* Now you can work with *vpp */
        *vpp = ...
        break;

        case PTR_TYPE_DOUBLEP:
        dpp = ptr;
        /* Now you can work with *dpp */
        *dpp = ...
        break;
      }
    ...
  }

      

0


source







All Articles