Given a typedef'd ptr type, how can I access the base type?
Eg consider an "array" of doubles:
typedef double* vec_t;
If I try to initialise like this:
void init_vec(int n, vec_t v){
v = (vec_t)malloc(n*sizeof(*vec_t));
//...
}
gcc doesn't exactly like that
error: expected expression before 'vec_t'
v = (vec_t)malloc(n*sizeof(*vec_t));
^
What would be the proper way to do this?
I could, of course, simply write v = (vec_t)malloc(n*sizeof(double));
, but that's not what I'm looking for.
First, don't cast the result of malloc()
in C. It returns a void pointer, which will be safely promoted to vec_t *
.
Second, *vec_t
is an attempt to dereference a type, which is semantically invalid. You need to dereference a variable of type vec_t
. Conveniently, you have one.
v = malloc(n * sizeof *v);
Edit: As @chqrlie pointed out, the malloc()
'd memory is immediately lost on return. The allocated address is assigned to v
, but the calling function's copy of v
is not overwritten.
There is a problem with void init_vec(int n, vec_t v)
: the function cannot return the allocated pointer to the caller. It should either take a pointer to the vec_t
, or return a value of type vec_t
.
A simple solution is:
vec_t init_vec(int n) {
vec_t v = malloc(n * sizeof *v);
//...
return v;
}
Hiding pointers behind typedefs is not recommended, it tends to make the code less readable and more error prone. Your vec_t
type should really be a structure that contains a size
member for the size of the array and a pointer to double
or a flexible array. You could also distinguish between the allocated length size
and the used portion length
:
typedef struct vec_t {
size_t size, length;
double a[];
} vec_t;
vec_t *init_vec(size_t n) {
vec_t *v = malloc(sizeof *v + n * sizeof(*v->a));
v->size = v->length = n;
for (size_t i = 0; i < n; i++) {
v->a[i] = 0;
}
return v;
}
Finally, since init_vec
allocates the vector, it should be given to a more explicit name such as create_vec
, new_vec
or allocate_vec
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.