Hi there!
I'm tackling linked lists for the first time, a topic that we haven't yet covered in my basic C course but is illustrated quite nicely in Standish's Data Structures, Algorithms & Software Principles In C.
I need some help with a function in my linked list test program. Basically it just returns the address of the nth node on list L:
since this is my first stab at really using pointers I'm not sure if everything is OK, but it seems to work alright. This is what I'm having trouble with: say you want to directly access a field of the nth node with getadrs, as in:Code:car *getdrs(car *L, int nodeNum) { // (car is the structure type for my parking garage program) if (L == NULL || nodeNum > getLength(L)) return NULL; else { car *N = L; int i = 1; // if nodeNum is 0, return address of the last node in L while (N->link != NULL && (i <= nodeNum || nodeNum == 0)) { N = N->link; ++i; } return N; } }
getdrs(List, 2)->link
this works fine as long as there is a 2nd node in the list. If the list is empty, or if there are less than 2 nodes in List, the function returns NULL, and the program obviously crashes.
What I'd rather have the program do in this situation is return the address of List itself- would this be at all useful? I realize you could prevent this kind of error by checking the validity of the function call with a preceding if statement, but I want to try and make the getdrs function immune to pointer access violations or w/e by returning the argument that was passed to it in the first place.



LinkBack URL
About LinkBacks



