user3482104
user3482104

Reputation: 59

Allocating memory to a node containing a struct

So say I have a node from a doubly linked list

typedef struct node
{
struct node *pPrev;
struct node *pNext;
struct record *data;
}Node;

and the following struct named record with a struct within that named songlength

typedef struct record
{
    char *artist;
    char *album;
    char *song;
    char *genre;
    struct songlength *length;
    int played;
    int rating;

}Record;

typedef struct songlength
{
    int mins;
    int secs;
}SongLength;

How would I go about allocating memory for something like this. I know how to do a simple malloc/make node for a single int in each node of a list.

 Node *makeNode (int newData)
{
    Node *pMem = NULL;

    pMem = (Node *) malloc (sizeof (Node));

    pMem -> data = newData;
    pMem -> pNext = NULL;

    return pMem;
}

At the current state I have no idea how to do this. As all my attempts result in a big mess of mixed up memory.

Upvotes: 1

Views: 1059

Answers (3)

barak manos
barak manos

Reputation: 30156

Instead of trying to call malloc correctly, change the definitions of your structures.

Change this:

struct record *data;

To this:

struct record data;

And this:

struct songlength *length;

To this:

struct songlength length;

Since these structures are not used as the actual nodes of the linked-list, there doesn't seem to be any good reason to allocate them dynamically (unless you intend to have some Node without a record, or some record without a songlength).

Dynamic memory allocation is useful when you know the exact amount of required data only during runtime (you don't have to dynamically-allocate "every structure out there").

Upvotes: 1

Gopi
Gopi

Reputation: 19874

Node *p = malloc(sizeof(NODE));

p->data = malloc(sizeof(struct record));
// Allocate memory to the pointers within this structure
p->data->artist = malloc(30);
p->data->length = malloc(sizeof(struct songLength));

Fill in the respective values to each of the structure members. Since you have char* as your structure members please make sure you allocate memory to them before storing some value in them.

Apart from memory allocating make sure you fill in proper values in the members as I see newdata is of type int it should be used to fill in member which is of type int as you are not doing it make sure you fix it.

After the memory is used please free the memory using free(pointer)

Upvotes: 0

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4051

Don't cast the result of malloc() and family.

pMem = malloc (sizeof (Node));// It is for first structure.

pMem ->data=malloc(sizeof(struct record));

pMem->data->lenght=malloc(sizeof(struct songLength));

First allocation you allocated the memory for the pMem. So in that data is a structure, so have to allocate the memory for that to access that structure member.

Upvotes: 1

Related Questions