Thursday, 15 May 2014

C struct pointer as argument: making permanent changes to the struct -



C struct pointer as argument: making permanent changes to the struct -

this code attempting order series of nodes priority, thing is, 1 homecoming function sort nodes, have done not persist. here simple code below followed output.

#include <stdio.h> #include <stdlib.h> #define null 0 typedef struct node{ struct node * next; struct node * prev; int priority; }node; struct node nodes[5]; struct node * head = null; node * function( node * phead, node * top){ node * pos = top; if(top == null){ top = phead; } else{ if(top->priority < phead->priority){ top = phead; phead->prev = pos->prev; phead->next = pos; pos->prev = phead; } while(phead->priority < pos->priority){ pos = pos->next; if(pos == null){ pos->next = phead; phead->prev = pos; phead->next = null; homecoming top; } } (pos->prev)->next = phead; phead->prev = pos->prev; phead->next = pos; pos->prev = phead; } homecoming top; } void printnodes(){ node * pos = head; while(pos != null){ printf("priority order!:::::%d\n", pos->priority); pos = pos->next; } } int main(){ nodes[0].priority = 10; nodes[1].priority = 9; nodes[2].priority = 8; nodes[3].priority = 7; nodes[4].priority = 6; nodes[0].next = null; nodes[1].next = null; nodes[2].next = null; nodes[3].next = null; nodes[4].next = null; nodes[0].prev = null; nodes[1].prev = null; nodes[2].prev = null; nodes[3].prev = null; nodes[4].prev = null; head = function(&nodes[0], head); printf("head %p\n", head); printf("priority order!:::::%d\n", head->priority); head = function(&nodes[1], head); printf("priority order!:::::%d\n", head->priority); head = function(&nodes[2], head); printf("priority order!:::::%d\n", head->priority); head = function(&nodes[3], head); printf("priority order!:::::%d\n", head->priority); head = function(&nodes[4], head); printf("priority order!:::::%d\n", head->priority); printnodes(); homecoming 0; }

output:

head 0x600c20 priority order!:::::10 segmentation fault (core dumped)

the segfault caused by:

if(pos == null){ pos->next = phead;

you dereference null pointer.

i have problem next code because of inconsistent variable names (top head , phead next node, etc).

c pointers types struct typedef

No comments:

Post a Comment