First of all, your code has some bugs, mainly that in standard C you can't do arithmetic on void
pointers (as commented by MikeCAT). Probably a more typical way to write it would be:
int *create_arr(int len) {
int *ptr = malloc((len + 1) * sizeof(int));
if (ptr == NULL) {
// handle allocation failure
}
ptr[0] = len;
return ptr + 1;
}
This is legal but no, it's not common. It's more idiomatic to keep track of the length in a separate variable, not as part of the array itself. An exception is functions that try to reproduce the effect of malloc
, where the caller will later pass back the pointer to the array but not the size.
One other issue with this approach is that it limits your array length to the maximum value of an int
. On, let's say, a 64-bit system with 32-bit int
s, you could conceivably want an array whose length did not fit in an int
. Normally you'd use size_t
for array lengths instead, but that won't work if you need to fit the length in an element of the array itself. (And of course this limitation would be much more severe if you wanted an array of short
or char
or bool
:-) )
Note that, as Andrew Henle comments, the pointer returned by your function could be used for an array of int
, but would not be safe to use for other arbitrary types as you have destroyed the alignment promised by malloc
. So if you're trying to make a general wrapper or replacement for malloc
, this doesn't do it.