Search code examples
cvariadic-functionsvariadicvariadic-macros

How can have an argument to a function be a type? (Similar to va_arg's second argument)


In the function va_arg for variadic functions, the second argument is just 'type'. When using this function, examples pass something like 'int'. How can I pass and use types in functions of my own? For example if I wanted to malloc a block of memory so that using brackets [ ] will use the correct offsets to what the user specified, is there a way to do this?


Solution

  • Functions can't. va_arg is a macro that invokes a lot of platform specific junk. But what you want to do might look something like this:

    #define mallocT(T, n) (malloc(sizeof(T) * (n)))
    

    where T is the type argument and n is the array size integer argument.