![]() |
| | #1 |
| Registered User Join Date: Oct 2002
Posts: 6
| Problem with pointers and linked lists Thanks in advance, Branden Code: #include <stdio.h>
#include <stdlib.h>
typedef struct node{
int number;
struct node *next;
struct node *prev;
} NODE;
void createlist(NODE *head, NODE *current, int number)
{
head = (NODE*)malloc(sizeof(NODE));
current = head;
current->number = 15;
current->next = current;
current->prev = current;
}
int main()
{
NODE *head = NULL;
NODE *current = NULL;
//create the first node
//head = malloc(sizeof(NODE));
//current = head;
//current->number = 15;
//current->next = current;
//current->prev = current;
//end first node creation
createlist(head, current, 15);
printf("%i\n", current->number);
return 0;
}
|
| bsimbeck is offline | |
| | #2 |
| Me want cookie! Join Date: Dec 2001
Posts: 680
| You need to pass the address of the pointer to make it work. This is because you change the pointer with the malloc function: Code: void createlist(NODE **head, NODE **current, int number)
{
*head = (NODE*)malloc(sizeof(NODE));
*current = *head;
(*current)->number = 15;
(*current)->next = *current;
(*current)->prev = *current;
}
createlist(&head, ¤t, 15);
|
| Monster is offline | |
| | #3 |
| Me want cookie! Join Date: Dec 2001
Posts: 680
| Some explanation: In main head is a pointer to NULL. When calling createlist a copy of the pointer is placed on the stack (it's also pointing to NULL). In the createlist function memory is allocated and the copy of head is pointing to the allocated memory. The original head pointer in main is still pointing to NULL. If you pass the address of the head pointer, the createlist function has access to the original pointer by dereferencing (place * before the variable), so the allocated memory can be assigned to the original head pointer in the main function. Same story for the "current" variable Some more info |
| Monster is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Pointers to pointers in linked lists | G4B3 | C++ Programming | 2 | 07-23-2008 03:54 AM |
| pointers and linked lists in place of arrays | kordric | C++ Programming | 8 | 05-14-2008 10:59 AM |
| Double pointers and linked lists. | simo_r | C Programming | 2 | 05-06-2008 04:25 AM |
| Request for comments | Prelude | A Brief History of Cprogramming.com | 15 | 01-02-2004 10:33 AM |
| Linked Lists & Pointers | fkheng | C Programming | 4 | 06-10-2003 07:26 AM |