Reputation: 59
I am currently attempting to use a doubly linked list to sort some data. I am having trouble creating a new node with the given data. Below was the code given to me:
#ifndef LIST_H_
#define List_H_
#define MAX_SYMBOL_LENGTH 7
struct order {
int id;
char symbol[MAX_SYMBOL_LENGTH];
char side;
int quantity;
double price;
};
typedef struct order* OrderPtr;
typedef struct onode* NodePtr;
struct onode {
OrderPtr data;
NodePtr next;
NodePtr prev;
};
This is the code that I have written using list.h as a header. Here is the code that seemingly keeps crashing:
#include "list.h"
NodePtr newNode(OrderPtr data){
NodePtr node = (NodePtr)malloc(sizeof(NodePtr));
//node->data = (NodePtr)malloc(sizeof(OrderPtr));
//*node->data = *data;
node->data = data;//This is the one I am having problems with
node->next = NULL;
node->prev = NULL;
return node;
}
It compiles fine but when I try and submit it to an online grader it says that it does not work. Here is my thought process,
and then assign the values of data passed from the function to the values in Node->Ptr. But I do not know how to allocate memory for NodePtr->data.
Upvotes: 0
Views: 2149
Reputation: 17427
NodePtr node = (NodePtr)malloc(sizeof(NodePtr));
Isn't doing what you are thinking. It's allocate space to hold a pointer same as sizeof(int*
), it's 4
bytes on 32-bit machine, usually.
You need to do NodePtr node = malloc(sizeof(struct onode));
instead of.
data
member should be result to a malloc(sizeof(struct order));
Also, don't cast result value from a malloc()
call.
Upvotes: 2
Reputation: 96
NodePtr
is a pointer to a node and not the node itself. You're only allocating enough memory for a pointer and not all the members of the onode structure. You'll want to call malloc
with sizeof(struct onode)
.
Upvotes: 1