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?
Asked
Active
Viewed 52 times
1
-
3`va_arg` is not a function but a macro, and this is typically how all such things are accomplished. They're usually not a good idea unless you have a very specific reason to want to do this, and a clear understanding of the language to know exactly what you are doing. – Nate Eldredge Aug 11 '19 at 02:44
-
2I don't understand what you mean by your last sentence. Can you add a specific example of what you want to be able to do? – Nate Eldredge Aug 11 '19 at 02:45
-
If I malloc a block, whatever I cast the pointer to will dictate where in memory an offset such as [1] or [2] return. If I want the user to be able to pass either a type or a number of bytes to use, is there any way to compute offsets in memory using brackets, or is the only way to use pointer arithmetic? – nevets Aug 11 '19 at 03:26
-
@nevets Using brackets **is** pointer arithmetic. `A[B]` is exactly equivalent to `*(A + B)`. – dbush Aug 11 '19 at 04:35
1 Answers
1
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.

Joshua
- 40,822
- 8
- 72
- 132
-
1@AnttiHaapala: You could, but should you? See https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Nate Eldredge Aug 11 '19 at 04:50