Hey all
I've got a problem adding a new node to a linked list. Firstly, here's the relevant code:
Code:
void addToList(Record *rptr)
{
Record *nnode;
if ((nnode = (Record *) malloc(sizeof(Record))) == NULL)
{
cerr << "Cannot allocate memory for new node.\n";
exit(EXIT_FAILURE);
}
nnode = rptr;
if (tnode == NULL)
tnode = nnode;
else
{
for (cnode = tnode; cnode->next != NULL; cnode = cnode->next)
;
cnode->next = nnode;
}
}
The problem is that when the code reaches the nnode = rptr; line, nnode ends up pointing to the address held in rptr. That results in me only being able to add one node, being as the address for the next pointer is the same as the last (if that makes sense).
If I cout the address of nnode before the assignment takes place, it always has a different memory address (which is what I want). However, is there a way to just assign the data in rptr to nnode, without making nnode point to the address? Not sure if that makes sense, but basically, I've got the following definitions for the structures:
Code:
typedef struct ir_record {
char cust_code[CUSTCHECKDIGIT + 1];
char part_num[PARTCHECKDIGIT + 1];
char qty[5];
} irRecord;
typedef struct d_record {
char cust_code[CUSTCHECKDIGIT + 1];
} dRecord;
typedef struct c_record {
char cust_code[CUSTCHECKDIGIT + 1];
char cust_name[CUSTNAMESIZE + 1];
char cust_addr[CUSTADDRSIZE + 1];
float balance;
float credit;
} cRecord;
typedef union current_record {
irRecord ir;
dRecord d;
cRecord c;
} mRecord;
typedef struct main_record {
char rec_type;
mRecord main;
struct main_record *next;
} Record;
Seems complex, but it's to solve an assignment problem. So as I say, is there a way to assign the data in rptr, to nnode, without having to perform a switch on rec_type to find out what data I need to assign (doing it manually of course)?
Hope this makes sense,
John.