Reputation: 672
I am working with a double linked list in C and I came across something that I realised I just always kind of accepted as fact or once knew the answer to and have now forgotten. This often happens to me when I start using pointers again and I end up having to re-learn them each time.
Here is the basics of my setup:
int main(void)
{
video *head = NULL;
video *tail = NULL;
char *buffer = NULL;
buffer = (char*)malloc(sizeof(MAX_TITLE_LENGTH));
printf("Enter a title: ");
fgets(buffer, MAX_TITLE_LENGTH, stdin);
insert(buffer, &head, &tail);
}
I have a structure:
typedef struct video
{
char title[MAX_TITLE_LENGTH];
struct video *prev;
struct video *next;
}video;
Prototype for insert:
int insert (char *title, video **head, video **tail);
and I am wondering why I have to pass the video *'s address specifically.
I know that the way I pass the char, it passes the address in memory of the beginning of the string. Why do I have to de-reference the head and tail a second time to access their values?
This is honestly more simple than I am thinking it is, I am sure of it, and I have my brain in a bad spot thinking about pointers.
Can anyone jar it loose?
Thanks.
Upvotes: 1
Views: 392
Reputation: 59627
It's because the function insert
might need to change what head
and tail
point to.
Remember that in C, function parameters are pass-by-value. This is why you pass a pointer to a struct
that you want to change in a function: providing a pointer allows your function access to the actual structure in memory.
But that pointer to the struct
is passed by value. What if you want to change what the pointer points to? You'll need an additional level of reference, or the memory that actually holds the pointer, so that it won't simply be copied. With the additional level if reference, you'll have access to the pointer to change it in the function, and can make the pointer point to something else.
You'll often see this in linked list code, that needs to modify e.g. the head
element: all the other elements in the list are - presumably - accessible by using the pointers contained in each node in the list, but if you need to e.g. insert a new element at the head, your function will need to change the head pointer. If you pass it in as a function parameter, you'll need it's address, otherwise the function would only be changing a copy, and the changes aren't reflected outside the function.
Upvotes: 5