Home > Software design >  Malloc'ing a double pointer structure inside a struct? [closed]
Malloc'ing a double pointer structure inside a struct? [closed]

Time:10-06

C noob here. I'm trying to initialize a simple struct as follows:

typedef struct person_s {
    char *fname;                 ///< first name of the person
    char *lname;                 ///< last name of the person
    char *handle;               ///< handle of the person
    struct person_s **friends;  ///< dynamic collection of friends
    size_t friend_count;        ///< current number of friends
    size_t max_friends;         ///< current limit on friends
} person_t;

I think I understand using malloc for every single member in this struct, except for the double pointer friends struct in it. How do I allocate memory for this double pointer?

Here's my malloc for the other data members:

person_t *newperson(char *fn, char *ln, char *han){
    person_t *p = NULL;
    p = malloc(sizeof(person_t));

    p->fname = malloc(strlen(fn)  1);
    strcpy(p->fname, fn);

    p->lname = malloc(strlen(ln)  1);
    strcpy(p->lname, ln);

    p->handle = malloc(strlen(han)  1);
    strcpy(p->handle, han);

    p->*friends = malloc(sizeof(*friends));

    p->friend_count = malloc(2*sizeof(friend_count));
    p->friend_count = 0;

    p->max_friends = malloc(2*sizeof(max_friends));
    p->friend_count = 0;
}

Edit: my bad, I forgot to include that this is inside a function that initializes this struct.

Edit1: In response to the comments, what I'm trying to achieve here is to make a dynamic "array" of friends that is pointed by the p->friends data member. Additionally, I have a dynamic hash table, would it be a good idea to use it as a collection for putting all the friends linked to this person? The concept of pointers and dynamic allocation is still somewhat confusing to me so sorry for misunderstanding.

CodePudding user response:

Single pointer is enough for dynamic collection:

struct person_s *friends; 

...

p->friends = malloc(max_friends * sizeof(struct person_s));
  • Related