Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc inside a structure

I've just started a course about C programming and I'm stuck with the malloc() function. I've a code to implement a linked list of segments.

#include <stdlib.h>
#include <stdio.h>

typedef struct{
  struct {
    double x, y;
  } point;
  void *next;
  void *prev;
} segment_t;

typedef struct {
  segment_t *first;
  segment_t *last;
} poly_t;

Now, if I want to allocate the memory for the struct segment_t, should I allocate also the memory for the two void pointers *next and *prev? And the same for *first and *last inside the poly_t structure?

Thanks for the help!

like image 436
InterMilan Avatar asked Sep 05 '25 03:09

InterMilan


2 Answers

malloc(sizeof(segment_t)) allocates enough memory for the entire structure, including x, y, next and prev.

It doesn't initialize any of those members, however. If you want next and prev to point to something, you will need to assign a pointer to them. Whether it's a freshly allocated pointer (malloc(...)) or an existing one (incl NULL) is up to you.

In this particular case, an instance of segment_t is a node of a doubly-linked list. As such, s->next and s->prev should be initialized to NULL until the node (segment) is added to the list.


As mentioned by @Vlad from Moscow, you shouldn't be using void* for the pointers, but the following:

typedef struct segment {
  struct {
    double x, y;
  } point;
  struct segment *next;
  struct segment *prev;
} segment_t;
like image 195
ikegami Avatar answered Sep 07 '25 23:09

ikegami


For starters it is unclear why within the structure the pointers have the type void *. This only confuses readers of the structure definition

typedef struct{
  struct {
    double x, y;
  } point;
  void *next;
  void *prev;
} segment_t;

Whether you mean

typedef struct{
  struct point{
    double x, y;
  } point;
  struct point *next;
  struct point *prev;
} segment_t;

or you mean

typedef struct segment {
  struct {
    double x, y;
  } point;
  struct segment *next;
  struct segment *prev;
} segment_t;

So change the structure definition accordingly to its usage.

If you want to allocate memory for an object of the type segment_t or poly_t then the object should be initialized ultimately. For example the pointers next, prev, first, and last initially can be initialized by NULL.

like image 22
Vlad from Moscow Avatar answered Sep 07 '25 22:09

Vlad from Moscow