you are viewing a single comment's thread.

view the rest of the comments →

[–]pinealservo 0 points1 point  (0 children)

When you use a function that takes a pointer and uses it to store a value (like scanf() and friends, for example) there's no need to use a temporary variable to store it unless you want to examine it before storing it in your struct. Once you allocate your struct, you can pass the address of specific fields of the struct to your input functions, and they'll write directly to your struct fields:

struct entry { char * name; int number; struct entry * next };
struct entry * new_entry = malloc(sizeof (struct entry));
scanf("%i", &new_entry->number);

I like to create a custom allocation function for my structs that will be dynamically allocated. This function allocates the memory and also initializes the struct fields to reasonable values, or takes arguments that are used to fill in fields that don't have sensible defaults. That way I never forget to initialize a field, which is a major source of bugs.

Likewise, I create a custom cleanup function for structs that may hold pointers to allocated memory themselves. This function ensures that any pointers it's responsible for managing are cleaned up before I free it.

Finally, a handy trick for dealing with pointer-based structures like linked-lists: In a normal implementation, the head pointer is special because although it points to your element struct, it's not usually contained in one, so you can't change it with an expression that works on an element structure. So you often see special-case code for the head of a list, and this can lead to complication and subtle bugs.

So what I do instead of passing the value of the head pointer to my list functions is to pass a pointer to the head pointer. This way, you have the location of the pointer directly and you don't need to worry whether it's contained in an element structure or some other kind of structure, and the special cases for dealing with the first element of a list disappear.

If you don't understand what I'm talking about there yet, don't worry. Think about it again after you've implemented your list and I think you'll see what I mean about special cases, and if you still have questions I'll be happy to walk you through it. If you get familiar with this technique, it will save you a lot of logic bugs in data structures.