Suppose I want to define a structure representing length of the vector and its values as:
struct Vector{
double* x;
int n;
};
Now,
In principle you're doing it correct already. For what you want you do need two malloc()
s.
Just some comments:
struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));
y->x = (double*)malloc(10*sizeof(double));
should be
struct Vector *y = malloc(sizeof *y); /* Note the pointer */
y->x = calloc(10, sizeof *y->x);
In the first line, you allocate memory for a Vector object. malloc()
returns a pointer to the allocated memory, so y must be a Vector pointer. In the second line you allocate memory for an array of 10 doubles.
In C you don't need the explicit casts, and writing sizeof *y
instead of sizeof(struct Vector)
is better for type safety, and besides, it saves on typing.
You can rearrange your struct and do a single malloc()
like so:
struct Vector{
int n;
double x[];
};
struct Vector *y = malloc(sizeof *y + 10 * sizeof(double));