Passing pointers to pointers..(wrt linked lists)

Started by
1 comment, last by Cat_B 21 years, 2 months ago
Hi, I am new at pointers. I want to pass the first pointer of a linked list to a function that creates it and then, in that function, pass it to another function that prints it.I either can't pass the proper thing to the print function or can't get the value back in the main program, I can do either but not both, unless I do what I do below, which works, but is just not right! Please if you know how to do this the right way, can you help? (or is this the way its normally done.....?) struct listNode{ int i; struct listNode *nextPtr; }; typedef struct listNode * ListNodePtr; int main(){ ...... ListNodePtr listNodePtr1=NULL; ...... listNodePtr1=createList(listNodePtr1, FILENAME1); //ARG! There has to be a better way!! ....... printList(listNodePtr1, FILENAME1); .... } ListNodePtr createList(ListNodePtr listNodePtr, char * filename){ ...... insert(&listNodePtr,i); printList(listNodePtr, filename); ..... return listNodePtr; //ARG! There has to be a better way!! } int printList(ListNodePtr listNodePtr, char * filename) { ....... while(listNodePtr!=NULL){ printf("%d-->",listNodePtr->i); listNodePtr=listNodePtr->nextPtr; } ....... return 1; } [edited by - Cat_B on January 27, 2003 12:33:34 AM] [edited by - Cat_B on January 27, 2003 12:34:19 AM]
Advertisement
Have the first parameter to createlist take a pointer to ListNodePtr - it would actually then be a pointer to a pointer. You can then defer the parameter to set the actual pointer passed. It''s exactly like passing a regular pointer to a function, expect you have an extra level of "pointer"ness. However, you hid the pointer is it''s own type, so that should make the code simplier to read for you:
void createList(ListNodePtr *p, char *filename){   insert(p, i);   printList(*p, filename);} 

If the insert function is coded correctly, than the original pointer in main should be correct. The class would look like createList(&listNodePtr1, FILENAME1);. You had the right idea originally with the insert function it seems, you just needed to expand that to the createList function as well

Here''s a quick little trick I use. If I need to alter the value of a type I''m passing, then I always add a level of indirection. So if I need to alter a regular variable, pass a pointer. If I need to alter a pointer type, pass a double-pointer. If I need to alter a double-pointer type, pass a triple-pointer etc. Another method is to pass it by reference instead of using an additional indirection level, but the syntax is uncomforting once you start passing pointer types by reference.
Hey, thank you SO much Zipster! It works like a charm
(Though, I have to admit I''m a little worried about getting my head wrapped around this...but ha, its almost midnight here, perhaps it will gel overnight!)

thanx again

This topic is closed to new replies.

Advertisement