cellka
cellka

Reputation: 129

Memory allocation inside already allocated memory in C

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?

Upvotes: 1

Views: 531

Answers (1)

Acorn
Acorn

Reputation: 26194

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.

Upvotes: 1

Related Questions