Re: Linked List & Dynamic Memory Allocation
- From: "Jonathan Wood" <jwood@xxxxxxxxxxxxxxxx>
- Date: Mon, 27 Aug 2007 12:51:10 -0600
First of all, none of the code you've provided makes a linked list, only an array.
If you have three nodes declared as you have, you could make them into a linked list like this:
for (int i = 0; i < (MAX - 1); i++)
m_nMode[i].next = &m_nMode[i+1];
m_nMode[MAX-1].next = NULL;
Although it seems kind of pointless given that these items are already in an array. Also, the m_ prefix is generally used to identify a variable as a class member variable, which your is not. That's a little confusing.
You could then add your new node to the list like this:
m_nMode[MAX-1].next = pNewRec;
pNewRec->next = NULL;
But you need to be careful here. Some of this linked list is declared on the stack and will dissappear as soon as your function returns, while one node in the list was allocated from the heap and will not dissappear until you pass it's address to free.
You can print all records this way:
for (nodes *p = m_nMode; p != NULL; i = p->next)
// print record pointed to by p
--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com
"one-trick-pony" <worldofpain.aamir@xxxxxxxxx> wrote in message news:1188238797.773199.307270@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi,
I am learning about data structures. I am somewhat confused and
unable to apply concept of dynamic memory allocation to my
application. This is what I am trying to do. I have an array of
structures as follows:
#define MAX 3
typdef struct node
{
char name[30];
struct node* next;
}nodes;
int main (void)
{
nodes m_node[MAX];
// play around with link list here add, remove, search items etc.
return 0;
}
I am trying to dynamically allocate memory if user chooses to enter
more than 3 records. I run following code to allocate memory
dynamically. Code is running fine.
nodes* pNewRec = (nodes *) malloc(sizeof(nodes));
if (!pNewRec)
{
printf("Unable to allocate memory\n");
exit(1);
}
I want to attach this new chunk of memory back to my original
m_node[MAX] array and then print all the records/items in linked
list. That is now m_node array has 4 records (one was created
dynamically). I am unable to attach new record entry to m_node. Need
help. Thanks
.
- Follow-Ups:
- Re: Linked List & Dynamic Memory Allocation
- From: one-trick-pony
- Re: Linked List & Dynamic Memory Allocation
- References:
- Linked List & Dynamic Memory Allocation
- From: one-trick-pony
- Linked List & Dynamic Memory Allocation
- Prev by Date: Re: CAsyncSocket's Send and Receive
- Next by Date: Re: mfc ext dll from path
- Previous by thread: Linked List & Dynamic Memory Allocation
- Next by thread: Re: Linked List & Dynamic Memory Allocation
- Index(es):
Relevant Pages
|
Loading