1
votes

I have two structs

struct point {
     double x;
     double y;   
};

struct points_set {
      int num_of_points;
      struct point *points; //an array of points sets 
}

I need to implement memory allocation for struct points_set. (i.e. to implement function struct point_set *alloc_points(struct point p_arr[], int size);)

As I see, we need to allocate memory twice, i.e. for point_set, and for the array of points that is inside the structure.

Firstly we allocate memory for the array that is supposed to be inside points_set, i.e.

struct point *arr_points = (struct point *)malloc(size * sizeof(point));

Then we allocate memory for the whole structure

struct point_set *setOfPoints = (struct point_set *)malloc(size * sizeof(struct points_set));

Finally, we make pointer from "setOfPoints" to "points"

setOfPoints->points = arr_points; 

Question: Is it correct?

1
You don't need to cast the result of malloc. - n. 1.8e9-where's-my-share m.
It may or may not be necessary to allocate struct points_set itself, it depends on your specific problem (and on the requirements of your assignment). - n. 1.8e9-where's-my-share m.

1 Answers

1
votes

Question: Is it correct?

Yes, but possibly you want:

struct point_set *setOfPoints = (struct point_set *)malloc(sizeof(struct points_set));

instead. In other words, do not multiply by size here, because you only want to allocate a single struct point_set, not many of them.